# 声明式规则

使用 UTF-8 JSON，根对象包含 `schema_version: 1` 和 `rules`。可选 `inventory` 提供包名到已观察版本的映射，`profiles` 提供名称到规则 ID 数组的映射。运行示例见 [examples/doctor.json](../examples/doctor.json)。

每条规则必须提供 `id` 和 `type`。ID、类别和 profile 名称接受 ASCII 字母、数字、点、短横线和下划线，最多 128 字符。可选字段有 `name`、`severity`（info/low/medium/high/critical）、`priority`（数值小的先执行）、`dependencies`、`enabled`、`timeout_ms` 和 `when`。选中规则时同时安排其前置检查。

| type | 专用字段 |
|---|---|
| platform | 无 |
| environment | `key`，可选 `expected` |
| path | `directory`，按完整 PATH 条目比对 |
| tool | `tool`，可选 `constraint`（默认 `*`） |
| dependency | `package`、`constraint`。默认使用 `inventory`，可指定 `snapshot`（根目录内的 `moon tree --json` 文件）及 `source`（例如 `registry`） |
| filesystem | `path`，可选 `access`（exists/read/write/execute）和 `kind`（any/file/directory） |
| configuration | `path`、`fields`。每项包含字段路径数组 `path` 和 `type`（text/number/boolean/object/array），可选 `required`、文本 `allowed`、数值 `minimum` 和 `maximum`（含端点），以及 `requires`（当前字段存在时必须存在的其他字段路径数组） |
| dns | `host` |
| tcp | `host`、`port`（1–65535） |
| resource | `metric`（cpu_count/memory_total_bytes/memory_available_bytes/disk_available_bytes/process_id）和非负整数 `minimum`。磁盘余量可另指定根目录内的目录 `path` |

条件使用单键对象，例如 `{"all":[{"present":"HOME"},{"not":{"equals":{"key":"CI","value":"false"}}}]}`。支持 `present`、`equals`、`all`、`any` 和 `not`。条件不匹配产生 Skipped。

在项目根目录运行 `moon tree --json > moon-tree.json` 后，将规则的 `snapshot` 指向 `moon-tree.json`。诊断读取已有快照并检查直接依赖的版本和来源类型。库调用方也可自行解析其他配置格式，再把 JSON 值交给 `validate_configuration_value`；内置配置读取器支持 JSON。

MoonBit 扩展可用 `rule` 与 `Registry::register` 注册异步回调。回调返回 Finding，可以附带证据和建议。完整示例见 [examples/custom_rule](../examples/custom_rule/main.mbt)。
