moonsystemdoctor

    Read-only development environment diagnostics with composable MoonBit rules

    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    6 hours ago
    Downloads
    2

    #MoonSystemDoctor

    Modular development environment diagnostics, implemented primarily in MoonBit.

    MoonSystemDoctor 是只读开发环境诊断库与 CLI:把工具链、依赖、文件、配置和网络检查组织成可组合规则,输出证据、稳定错误码和修复建议。适用于项目启动前检查及 CI 环境预检。

    仓库地址保留 moonsystermdoctor 的既有拼写;产品名为 MoonSystemDoctor,模块名为 mik1e80/moonsystemdoctor。

    #已实现

    能力实现范围
    核心模型Passed / Warning / Failed / Skipped / Unsupported / Error,严重程度、证据、建议、耗时
    规则与调度注册/注销/启停、优先级、DAG 验证、依赖阻塞、单项错误隔离、异步超时、取消令牌、总预算
    条件有界 AND / OR / NOT、变量存在性与相等判断
    环境与工具链OS/架构、环境变量、PATH 完整条目检查,包括 moon/moonc/git/cc/clang/gcc 的版本命令
    依赖显式版本清单或 moon tree --json 快照、SemVer 约束和来源检查
    文件与配置根目录边界、文件类型和权限、有界 UTF-8 读取、JSON 类型、数值范围与字段依赖
    网络与资源显式授权的 DNS/TCP、CPU 数、内存总量和可用量、目录所在磁盘空间、当前进程 ID
    报告与 CLIText/JSON/Markdown、敏感证据脱敏、profile/category/config、稳定退出码

    资源计数器使用一个小型 C 系统接口文件;规则、解析、版本判断、调度、CLI、报告和验证脚本均为 MoonBit。 平台验证范围见 兼容性,安全限制见 安全模型。

    #快速开始

    需要 MoonBit 编译器 0.10.17+d971670cd(本仓库固定验证版本)、Native C 编译器及 Git。CI 使用相同版本,不自动升级本机工具链。

    git clone https://github.com/mik1e80/moonsystermdoctor.git cd moonsystermdoctor moon update moon check --target native --deny-warn moon run cmd/doctor -- check moon run cmd/doctor -- rules list moon run cmd/doctor -- version

    默认检查 OS/架构、Moon、MoonBit 编译器、Git、moon.mod 可读性和三项资源。检查其他项目可使用 --root /path/to/project。使用旧格式的项目可自行声明 moon.mod.json 文件规则。网络探测需要显式启用。

    moon run cmd/doctor -- check --config examples/doctor.json --profile development moon run cmd/doctor -- check --category toolchain --jobs 4 --format json moon run cmd/doctor -- check --config examples/moon-dependency.json --format json moon run cmd/doctor -- check --config examples/doctor.json --profile network --allow-network moon run cmd/doctor -- check --config examples/doctor.json --profile development --format markdown moon run cmd/doctor -- check --config examples/failure.json

    最后一条命令有意返回 1,演示缺失文件、依赖阻塞和独立规则继续执行。examples/doctor.json 中的依赖版本为演示观测数据,不声称已安装该软件包。

    #构建独立 CLI

    moon build --target native --release cmd/doctor

    产物:_build/native/release/build/cmd/doctor/doctor.exe(Moon 的 Native 产物在 Unix 上也使用此扩展名)。可将其复制/重命名为 moon-system-doctor,Windows 使用 .exe。

    退出码含义
    0无失败或执行异常;默认允许警告/跳过/不支持
    1存在 Failed;--strict 下也包括 Warning/Skipped/Unsupported
    2参数/配置错误或规则执行 Error;高于诊断失败优先级

    #库和扩展规则

    在另一个 MoonBit 项目中安装 0.1.0:

    moon add mik1e80/moonsystemdoctor@0.1.0

    在 moon.pkg 中导入 mik1e80/moonsystemdoctor 即可使用诊断 API。需要真实宿主探测时,另外导入 mik1e80/moonsystemdoctor/native,并使用 Native 后端。 examples/custom_rule/main.mbt 展示第三方包如何定义异步回调、注册并运行规则:

    moon run examples/basic moon run examples/custom_rule

    公开 API 由根目录及各包的 pkg.generated.mbti 描述。宿主集成可实现 Platform Trait,或使用 MockPlatform 构造可重复故障环境。

    #验证与文档

    按本次开发要求,仅执行指定关键测试和 CLI 验证,不运行全量测试。三平台 CI 也使用明确文件选择。具体命令和证据见 测试说明。

    Apache-2.0,见 LICENSE。

    Platform

    pub(open) trait Platform {
    fn facts(Self) -> Map[String, String]
    async fn inspect(Self, Probe) -> Finding
    async fn read_text(Self, String, Int) -> String
    }

    Implementations must confine file access, bound I/O, and avoid shell evaluation.

    DoctorError

    pub(all) suberror DoctorError {
    DoctorError(String)
    }

    Access

    pub(all) enum Access {
    Exists
    Read
    Write
    Execute
    }

    Cancellation

    pub struct Cancellation {
    // private fields
    }

    Cancellation::cancel

    fn Cancellation::cancel(self : Cancellation) -> Unit

    Cancellation::new

    Condition

    pub(all) enum Condition {
    Always
    Present(String)
    Equals(String, String)
    All(Array[Condition])
    Any(Array[Condition])
    Not(Condition)
    }

    Conditions inspect caller-provided facts, never execute commands.

    Condition::evaluate

    fn Condition::evaluate(self : Condition, facts : Map[String, String], max_depth? : Int, max_nodes? : Int) -> Bool raise DoctorError

    Configuration

    pub struct Configuration {
    registry : Registry
    inventory : Map[String, String]
    profiles : Map[String, Array[String]]
    }

    Configuration::context

    fn Configuration::context(self : Configuration, platform : &Platform, allow_network? : Bool) -> Context

    Configuration::parse

    fn Configuration::parse(source : String, platform : &Platform) -> Configuration raise DoctorError

    Strict, versioned data-only rules. No config field can supply commands or scripts.

    Configuration::selection

    fn Configuration::selection(self : Configuration, profile? : String, category? : String) -> Array[String] raise DoctorError

    Context

    pub(all) struct Context {
    facts : Map[String, String]
    allow_network : Bool
    }

    A run snapshot supplied by the caller; no ambient environment is read here.

    DiagnosticResult

    pub(all) struct DiagnosticResult {
    rule_id : String
    category : String
    severity : Severity
    finding : Finding
    duration_ms : Int64
    }

    Evidence

    pub(all) struct Evidence {
    key : String
    value : String
    sensitive : Bool
    }

    Field

    pub(all) struct Field {
    path : Array[String]
    kind : FieldType
    required : Bool
    allowed : Array[String]
    minimum : Double?
    maximum : Double?
    requires : Array[Array[String]]
    }

    FieldType

    pub(all) enum FieldType {
    Text
    Number
    Boolean
    Object
    Array
    }

    Finding

    pub(all) struct Finding {
    status : Status
    code : String
    message : String
    evidence : Array[Evidence]
    remediation : String
    }

    MockPlatform

    pub struct MockPlatform {
    snapshot : Map[String, String]
    observations : Map[String, Finding]
    files : Map[String, String]
    }

    The mock does no I/O. Keys identify probes using probe_key.

    MockPlatform::facts

    fn MockPlatform::facts(self : MockPlatform) -> Map[String, String]

    MockPlatform::inspect

    async fn MockPlatform::inspect(self : MockPlatform, probe : Probe) -> Finding

    MockPlatform::new

    fn MockPlatform::new(facts? : Map[String, String], observations? : Map[String, Finding], files? : Map[String, String]) -> MockPlatform

    MockPlatform::read_text

    async fn MockPlatform::read_text(self : MockPlatform, path : String, limit : Int) -> String

    PathKind

    pub(all) enum PathKind {
    RegularFile
    Directory
    }

    Probe

    pub(all) enum Probe {
    File(String, Access)
    TypedFile(String, Access, PathKind)
    Tool(String, String)
    Dns(String)
    Tcp(String, Int)
    Resource(String, Int64)
    DiskAt(String, Int64)
    }

    Registry

    pub struct Registry {
    rules : Array[Rule]
    max_rules : Int
    }

    Registry::get

    fn Registry::get(self : Registry, id : String) -> Rule?

    Registry::list

    fn Registry::list(self : Registry) -> Array[Rule]

    Registry::new

    fn Registry::new(max_rules? : Int) -> Registry raise DoctorError

    Registry::plan

    fn Registry::plan(self : Registry, selected? : Array[String]) -> Array[Rule] raise DoctorError

    Validate the complete graph before any checks run; selection includes prerequisites.

    Registry::register

    fn Registry::register(self : Registry, value : Rule) -> Unit raise DoctorError

    Registry::run

    async fn Registry::run(self : Registry, ctx : Context, selected? : Array[String], cancellation? : Cancellation, budget_ms? : Int, jobs? : Int) -> Array[DiagnosticResult]

    Run ready checks in bounded batches and return results in plan order. Async callbacks must yield: CPU-bound infinite callbacks cannot be preempted.

    Registry::set_enabled

    fn Registry::set_enabled(self : Registry, id : String, enabled : Bool) -> Unit raise DoctorError

    Registry::unregister

    fn Registry::unregister(self : Registry, id : String) -> Unit raise DoctorError

    ReportMetadata

    pub(all) struct ReportMetadata {
    started_at_unix_ms : UInt64
    tool_version : String
    os : String
    backend : String
    }

    Requirement

    pub struct Requirement {
    lower : (Version, Bool)?
    upper : (Version, Bool)?
    prerelease_cores : Array[(Int, Int, Int)]
    }

    Requirement::accepts

    fn Requirement::accepts(self : Requirement, version : Version) -> Bool

    Requirement::conflicts

    fn Requirement::conflicts(self : Requirement) -> Bool

    Requirement::parse

    fn Requirement::parse(text : String) -> Requirement raise DoctorError

    Rule

    pub(all) struct Rule {
    id : String
    name : String
    category : String
    severity : Severity
    priority : Int
    dependencies : Array[String]
    enabled : Bool
    timeout_ms : Int
    execute : async (Context) -> Finding
    }

    Severity

    pub(all) enum Severity {
    Info
    Low
    Medium
    High
    Critical
    }

    Severity::label

    fn Severity::label(self : Severity) -> String

    Status

    pub(all) enum Status {
    Passed
    Warning
    Failed
    Skipped
    Unsupported
    Error
    } derive(Eq)

    A capability that was not tested is never a passing diagnosis.

    Status::equal

    fn Status::equal(Status, Status) -> Bool
    automatically derived

    Status::label

    fn Status::label(self : Status) -> String

    Status::not_equal

    fn Status::not_equal(x : Status, y : Status) -> Bool
    automatically derived

    Summary

    pub(all) struct Summary {
    passed : Int
    warning : Int
    failed : Int
    skipped : Int
    unsupported : Int
    errors : Int
    }

    Summary::exit_code

    fn Summary::exit_code(self : Summary, strict? : Bool) -> Int

    Exit code 2 denotes execution errors; 1 denotes diagnosed failures; 0 otherwise.

    Version

    pub struct Version {
    major : Int
    minor : Int
    patch : Int
    prerelease : Array[String]
    }

    Version::compare

    fn Version::compare(self : Version, other : Version) -> Int

    Version::parse

    fn Version::parse(text : String) -> Version raise DoctorError

    conditional

    fn conditional(value : Rule, condition : Condition) -> Rule

    configuration_rule

    fn configuration_rule(id : String, platform : &Platform, path : String, fields : Array[Field]) -> Rule raise DoctorError

    context

    fn context(facts? : Map[String, String], allow_network? : Bool) -> Context

    default_configuration

    fn default_configuration(platform : &Platform) -> Configuration raise DoctorError

    dependency_rule

    fn dependency_rule(id : String, name : String, constraint : String) -> Rule raise DoctorError

    Installed versions are supplied as facts named dependency.<name>. This checks observations; it does not resolve or install packages.

    display_text

    fn display_text(text : String, limit? : Int) -> String

    Bound and sanitize display strings, including terminal controls.

    environment_rule

    fn environment_rule(id : String, key : String, expected? : String) -> Rule

    Check presence without putting the variable's value in a report.

    field

    fn field(path : Array[String], kind : FieldType, required? : Bool, allowed? : Array[String], minimum? : Double, maximum? : Double, requires? : Array[Array[String]]) -> Field

    finding

    fn finding(status : Status, code : String, message : String, evidence? : Array[Evidence], remediation? : String) -> Finding

    Construct a finding. Evidence should contain observations, never credentials.

    inspect_path

    fn inspect_path(value : String, required : String, windows? : Bool) -> Finding

    PATH entries are compared as complete entries; substring matches are rejected.

    path_rule

    fn path_rule(id : String, required : String, windows? : Bool) -> Rule

    platform_check

    fn platform_check(id : String, category : String, platform : &Platform, probe : Probe, timeout_ms? : Int) -> Rule

    Build a host-backed rule. Network probes are opt-in on every run.

    platform_rule

    fn platform_rule() -> Rule

    probe_key

    fn probe_key(probe : Probe) -> String

    read_moon_dependency

    fn read_moon_dependency(content : String, name : String) -> (String, String)? raise DoctorError

    Read a direct dependency from a successful Moon module graph export.

    remediation_for

    fn remediation_for(code : String) -> String

    Stable codes decouple integrations and localized guidance from message wording.

    render_report

    fn render_report(results : Array[DiagnosticResult], format : String, secrets? : Array[String], max_bytes? : Int, metadata? : ReportMetadata) -> String raise DoctorError

    Rendering is deterministic when results and report metadata are supplied. Known secrets are removed before truncation. Evidence keys are independently redacted.

    report_metadata

    fn report_metadata(started_at_unix_ms? : UInt64, os? : String, backend? : String) -> ReportMetadata

    rule

    fn rule(id : String, category : String, execute : async (Context) -> Finding, name? : String, severity? : Severity, priority? : Int, dependencies? : Array[String], enabled? : Bool, timeout_ms? : Int) -> Rule

    safe_relative

    fn safe_relative(path : String) -> Bool

    Relative paths only; native adapters additionally validate canonical targets. Backslashes are treated as separators on every OS to avoid portable-config surprises.

    secret_values

    fn secret_values(facts : Map[String, String]) -> Array[String]

    Environment secrets are collected only for redaction, never serialized.

    sensitive_key

    fn sensitive_key(key : String) -> Bool

    summarize

    fn summarize(results : Array[DiagnosticResult]) -> Summary

    tool_version

    let tool_version : String

    Version shared by the CLI and its reports.

    validate_configuration

    fn validate_configuration(text : String, fields : Array[Field]) -> Finding

    validate_configuration_value

    fn validate_configuration_value(value :
    Json
    , fields : Array[Field]) -> Finding

    Apply the field schema to an already decoded value.

    validate_input

    fn validate_input(text : String, max_bytes? : Int, max_depth? : Int) -> Unit raise DoctorError

    A lightweight scan bounds nesting before invoking the JSON parser.