docs: define the closed public Analysis boundary

Add ADR-0069 and replace the program-only Analysis v3 shape in place with the
one public projection consumed by independent static tools: project entry and
snapshot identity, exact source, document AST, heading scope facts, anchors,
functions, calls, resources and stateful references. Update the Markdown
profile, reference and observation specs to point at the single resolver and
the same encoder/digest rule.
This commit is contained in:
cflmy committed 2026-11-25 09:39:26 +08:00
1 parent e6066e6ba9
commit 88d7cd3414
6 files changed
+1153 -444

No files matched your search

+80
View File
@@ -0,0 +1,80 @@
# ADR-0069 — One public Analysis boundary for independent static tools
Status: Accepted for implementation on the pre-stable 3.0 line (2026-11-25).
## Context
Issue [#10](https://git.cflmy.cn/cflmy/marqdo-cli/issues/10) audited the
public Analysis contract at `master@e6066e6`. The CLI already restricts
View/Lint-style consumers to installed Tools, but the emitted
`marqdo.analysis` document only exposed program IR. It omitted the Markdown
document AST, the exact source text, the entry/context snapshot, heading
scopes and anchors, complete section ranges, and reference resolution states.
Independent tools therefore had to re-parse Markdown, guess section ends or run
a second non-public analysis path. Two implementations of Markdown-link
resolution existed (`analysis.rs` and `commands.rs`), the Analysis `unresolved`
state could not distinguish "not loaded" from "missing", and `analysis.rs`
re-read `marqdo.lock` after preparation.
## Decision
`marqdo check ENTRY --emit PATH` remains the only public static-analysis
producer. Before the first stable release, replace `marqdo.analysis` revision 3
in place under ADR-0068. There is one shape, one producer and one validation
path; retired fields are not read.
The projection is built by one typed encoder from the same
`project_prepare::prepare` facts consumed by `check`, `inspect`, `run` and
`call`:
* `project.entry_module_id`, `manifest_digest`, the captured `lock_digest`,
stdlib identity and the static extension identities that actually took part
in preparation;
* each loaded module's exact UTF-8 `source` and its `source_digest`, plus the
public Markdown AST (`document`) in the shape already described by
`spec/markdown-profile.md`;
* one heading index: canonical path, parent, effective mode, mode origin and
source unit, heading span, complete section span and the function created by
an Exec H2;
* the anchor map, functions, explicit imports, resources, static call bindings
and diagnostics;
* every Markdown link through one scoped `document_refs` resolver that
distinguishes `resolved`, `not_loaded`, `missing`, `ambiguous`, `external`,
`outside_scope` and `invalid`.
The resolver is a pure function over an explicit catalog. Ordinary Analysis
uses the loaded-module catalog and never opens a link target. `check --refs`
and `inspect --refs` build a separate, explicitly limited catalog for direct
link targets and append diagnostics; they do not change the ordinary Analysis
module set and never execute or import a target.
Identity strings stay the current presentation for names that do not contain
the structural separators. Unit paths are now also exposed as the structured
`path` array, and identity display escapes `/`, `#` and `%` inside a path
segment so `<module>#<seg>/<seg>` cannot collide with a segment containing
`/`. `Function.local_name` and `namespace` remain structured fields; consumers
must not split display ids.
The public source field is an explicit local artifact. It is written with
owner-only permissions where the platform supports them, is never copied into
Observation, is never printed by default, and its digestion is the exact
UTF-8 bytes (SHA-256). Observation continues to bind to the SHA-256 of the
exact bytes emitted by `check --emit` with the same static options.
## Security and verification
The boundary remains non-executing: no plugin shared library, worker, foreign
kernel, network request or implicit module load. `--emit` publishes atomically
through an owner-only exclusive temporary file and rename, refuses to overwrite
a loaded source, manifest, lock file, symlink to one, or a hard link to one,
and only removes a previous artifact at a caller-specified output path under
the same guard.
Production checks local typed invariants and the canonical encoder; an
independent Python consumer validates the emitted bytes against the published
JSON Schema and semantic invariants, and mutation fixtures prove that missing
required fields, stale same-revision artifacts, tampered digests/spans,
duplicate ids, wrong ownership and invalid reference states are rejected.
`docs/STATUS.md` records exactly what was executed on which SHA; the
pre-stable line makes no compatibility promise for consumers linked to the
retired shape.
+395 -125
View File
@@ -1,20 +1,43 @@
# Marqdo Analysis # Marqdo Analysis
Current public contract for `marqdo check --emit PATH`. Every project emits Current public contract for `marqdo check --emit PATH`. Every project emits
`marqdo.analysis` with `schema_version: 3`. `marqdo.analysis` with `schema_version: 3`. The contract is implemented by
[ADR-0069](../docs/adr/0069-public-analysis-boundary.md); it replaces the
program-only Analysis shape in place. Retired artifacts with the same revision
are rejected because every field below is required.
## 1. Invariants ## 1. Invariants
`check --emit`: `check --emit`:
* never executes the document, loads a plugin shared library, starts a foreign * never executes the document, opens a plugin shared library, starts a worker
kernel or imports a module implicitly; or foreign kernel, accesses the network, or imports a module implicitly;
* validates the loaded program first; on a compile error it writes no artifact * validates the prepared program first; on a compile or load error it writes
and removes an existing artifact at the target path; no artifact and only removes a previous artifact at the caller-specified
* writes atomically through a temporary file and rename; output path when that path is a safe output (see §8);
* contains no absolute machine paths, timestamps, PIDs or other environmental * writes through an owner-only exclusive temporary file in the target directory
data, so the same logical project emits byte-identical Analysis from and renames it into place atomically;
different checkout directories and is safe to compare across machines. * contains no absolute machine paths, timestamps, PIDs, random ids or other
environmental data, so the same logical project emits byte-identical
Analysis from different checkout directories;
* exposes only facts that one of `check`, `inspect`, `run` or `call` already
consumes through `project_prepare::prepare`. There is no second parser,
second call-binding pass or tool-specific branching.
`source` is present because it is the one artifact that lets a reader slice
every span without knowing package-cache or stdlib layouts. It contains only
modules that the loader already read statically; no extra file, asset or
binary is read. Treat an emitted Analysis as sensitive local source data:
`--help` and this specification say so, and the CLI neither uploads nor logs
it.
`AnalysisDigest` is the lowercase hex SHA-256 of the exact UTF-8 bytes written
by `check --emit` (pretty JSON), represented in Observation as
`sha256:<64 hex>`. Diagnostics and every static option that changes the
projection are part of those bytes. `run`/`call` bind to the same projection
with the same static options; a `--refs` invocation adds diagnostics and
therefore has a different digest, and must not be substituted for the ordinary
artifact.
## 2. Top-level shape ## 2. Top-level shape
@@ -24,59 +47,82 @@ Current public contract for `marqdo check --emit PATH`. Every project emits
"schema_version": 3, "schema_version": 3,
"producer": { "producer": {
"name": "marqdo", "name": "marqdo",
"version": "<crate version>", "version": "<product version>",
"markdown_profile": "marqdo.md.v1" "markdown_profile": "marqdo.md.v1"
}, },
"project": { "project": {
"root_id": "root:quantum@0.1.0", "root_id": "root:demo@0.1.0",
"identity_kind": "manifest", "identity_kind": "manifest",
"entry_module_id": "root:demo@0.1.0::index.mq.md",
"lock_digest": "sha256:<64 hex>", "lock_digest": "sha256:<64 hex>",
"stdlib": { "manifest_digest": "sha256:<64 hex>",
"version": "0.1.0", "stdlib": null,
"digest": "sha256:<64 hex>", "extensions": []
"instance_id": "std:marqdo-stdlib@0.1.0#<64 hex>"
}
}, },
"modules": [], "modules": [],
"diagnostics": [] "diagnostics": []
} }
``` ```
`project.identity_kind` is: ### 2.1 Project identity and snapshot
| Kind | `root_id` | Meaning | | Field | Meaning |
|---|---|---| |---|---|
| `manifest` | `root:<project.name>@<project.version>` | Logical identity of a project with `marqdo.yaml`. Moving the checkout or a Git clone does not change it. | | `root_id` | `root:<name>@<version>` for a project with `marqdo.yaml`; `sha256:<64 hex>` content snapshot without one. A snapshot is not a persistent project identity. |
| `workspace_snapshot` | `sha256:<64 hex>` | No manifest. Digest of sorted `(module_id, source_digest)` pairs; identifies content, not a persistent project. | | `identity_kind` | `manifest` or `workspace_snapshot`. |
| `entry_module_id` | The canonical id of the module loaded from `ENTRY`; it must occur exactly once in `modules`. A second entry of the same project produces its own Analysis and is never merged by basename. |
| `lock_digest` | `sha256:` + SHA-256 of the exact `marqdo.lock` bytes captured during preparation; `""` only when no lock file exists. A read failure is a load error, never an empty digest. |
| `manifest_digest` | `sha256:` + SHA-256 of the exact `marqdo.yaml` bytes captured during preparation; `""` when there is no manifest. This distinguishes equal name/version projects with different static configuration. |
| `stdlib` | `null`, or the verified bundle `{version, digest, instance_id}` actually used by this load. |
| `extensions` | Static extension identities that participated in preparation, sorted by `(kind, name, logical_owner, manifest_digest)`. See §2.2. |
`project.lock_digest` is the SHA-256 of the exact `marqdo.lock` bytes prefixed Manifest and lock bytes are read once while loading. Analysis never re-reads
with `sha256:`, or `""` when there is no lock. It is not a logical identity. them; a concurrent edit cannot make the artifact claim bytes other than the
snapshot that determined the program.
`project.stdlib` records the verified bundled standard library identity used by ### 2.2 Extension identity
this load: declared version, content digest and package instance id. It is
`null` when no bundle was available. A digest mismatch is a hard load error, so
an Analysis artifact can only name a bundle whose bytes matched the manifest.
`AnalysisDigest` is the lowercase hex SHA-256 of the exact UTF-8 bytes written
by `check --emit` (pretty JSON). This is what Observation binds to
`source.analysis_digest`; an independent consumer can verify it by hashing the
file. Diagnostics and any configuration options that change the projection are
part of that digest.
Module ids are `<package instance>::<package-relative path>` (ADR-0008) and are
scoped by `project.root_id`. A module id alone is not a cross-project symbol.
## 3. Modules
The module object is unchanged from Analysis v1 except for `resources`:
```json ```json
{ {
"id": "root:res@0.1.0::index.mq.md", "kind": "plugin",
"package_instance_id": "root:res@0.1.0", "name": "example.echo",
"version": "0.1.0",
"logical_owner": "root:demo@0.1.0",
"source": "./plugin",
"manifest_digest": "sha256:<64 hex>",
"artifact_digest": "sha256:<64 hex>",
"selected_target": "x86_64-unknown-linux-gnu"
}
```
`kind` is `plugin`, `kernel` or `provider`. Declared extensions use the lock v4
identity that was validated during preparation; explicit `--plugin` descriptors
are included with their verified manifest identity, `source: "--plugin"` and
`logical_owner: "cli"`. No secret, physical path, handle, signature or grant is
projected. Two exports of the same package are one identity; equal export names
in different packages remain distinct.
### 2.3 Module paths and ordering
Modules are sorted by canonical `id`. `id` is
`<package instance>::<package-relative path>` and is scoped by
`project.root_id`. `relative_path` must be non-empty UTF-8 with `/`
separators, contain no empty, `.` or `..` segment and no OS absolute, drive or
UNC prefix. Valid names such as `foo..bar.mq.md` are accepted; a file name that
cannot be represented losslessly is rejected rather than silently rewritten.
## 3. Module shape
```json
{
"id": "root:demo@0.1.0::index.mq.md",
"package_instance_id": "root:demo@0.1.0",
"relative_path": "index.mq.md", "relative_path": "index.mq.md",
"source_digest": "<64 hex of exact source bytes>", "source_digest": "<64 hex SHA-256 of source bytes>",
"source": "<exact UTF-8 source text>",
"document": {"kind": "document", "span": {"start": 0, "end": 0}, "children": []},
"units": [], "units": [],
"anchors": [],
"functions": [], "functions": [],
"imports": [], "imports": [],
"references": [], "references": [],
@@ -85,119 +131,343 @@ The module object is unchanged from Analysis v1 except for `resources`:
} }
``` ```
Modules are sorted by `id`; functions, units and calls keep document order and `source_digest` is the lowercase hex SHA-256 of the decoded UTF-8 bytes of
the v1 semantic node shapes (`assign`, `expression`, `branch`, `loop`, `source`. BOM, CRLF, missing trailing newline and NUL bytes are preserved in
`return`; literals, variables, lists, records, unary/binary, member, index, `source`; JSON escaping changes the encoding only, not the decoded bytes.
call). The v1 `call_site` node was retired with RFC-LANG-0002: calls are Every `span` in the module indexes `source`.
`call` expressions inside an `assign`/`expression`/`return`/condition body, not
a separate statement. `imports`, `references` and `calls` remain static facts; a
Markdown reference is not a call. `effects` remains `["unknown"]` (a
conservative summary, not a purity proof).
`calls[]` is projected from the single prepared call binding ### 3.1 Document AST
(`spec/callable-resolution.md` §6): `state` remains
`function`/`builtin`/`plugin`/`unresolved`, and official stdlib aliases such as
`打印` are reported as `function` targets because that is the implementation
that runs. The private `CallBindingTable` is not serialized; Analysis's
schema and version are unchanged.
An `assign` node keeps the v1 string `target` for a local rebinding. Addressable `document` is the public shape already defined by
memory adds one additive target form (ADR-0022); consumers that only understand `spec/markdown-profile.md` §5, emitted by an explicit projector and shared with
local assignments can ignore an object target: `inspect --ast`. Every node has `kind`, `span` and `children` (leaves use `[]`).
Leaves carry `literal` where the profile defines one. Attribute rules:
```json | Kind | Attributes |
{"kind":"assign", |---|---|
"target":{"kind":"index", | `document`, `block_quote`, `paragraph`, `strong`, `emph`, `strikethrough`, `table_cell` | none |
"base":{"kind":"variable","name":"内存","span":{"start":23,"end":26}}, | `front_matter` | `literal` |
"index":{"kind":"literal","type":"int","value":"0","span":{"start":27,"end":28}}, | `list` | `ordered`, `start` (`null` for bullet), `tight` |
"span":{"start":23,"end":29}}, | `item` | `task` (`null`, `true`, `false`) |
"value":{"kind":"literal","type":"int","value":"7","span":{"start":32,"end":33}}, | `heading` | `level` (1-6), `setext` |
"span":{"start":18,"end":35}} | `text`, `math_block`, `html_block`, `html_inline` | `literal` |
``` | `code` | `ticks` (delimiter length), `literal` |
| `code_block` | `fenced`, `info`, `literal` |
| `math` | `display`, `literal` |
| `link`, `image` | `url`, `title` |
| `table` | `alignments` (`none`, `left`, `center`, `right`) |
| `table_row` | `header` |
| `thematic_break`, `soft_break`, `line_break` | none |
| `other` | `tag`, optional `literal`, children preserved |
`target.kind` is `"index"`; `base` and `index` use the same expression node The root `document` span covers the whole source including a BOM. All node
shapes as every other expression. Analysis is static: it records the place but spans are half-open UTF-8 byte offsets, `start <= end <= source.len()` and on
never allocates a region or executes the write. UTF-8 boundaries. Container spans follow the parser source map, including its
documented empty/synthetic exceptions; semantic validation checks the
invariants that hold and does not pretend `literal` is byte-identical to the
span (entities, escapes and code whitespace may be normalised). HTML, links and
code blocks are inert data.
## 4. Resources ### 3.2 Units and heading scopes
`resources` is an array, not a count. The projection includes exactly the `units` is in document order with the root first:
resource kinds represented by `marqdo-ir::Resource`; it does not invent table,
HTML or link resources.
```json ```json
{ {
"id": "root:res@0.1.0::index.mq.md#resource:formula-1", "id": "root:demo@0.1.0::index.mq.md#力学/计算力",
"module_id": "root:res@0.1.0::index.mq.md", "path": ["力学", "计算力"],
"unit_id": "root:res@0.1.0::index.mq.md#calc", "parent_id": "root:demo@0.1.0::index.mq.md#力学",
"kind": "formula", "kind": "function",
"span": {"start": 30, "end": 44}, "name": "计算力",
"content_digest": "<64 hex>", "level": 2,
"language": null, "mode": "exec",
"display": true "mode_origin": "explicit",
"mode_source_unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力",
"heading_span": {"start": 10, "end": 30},
"span": {"start": 10, "end": 90},
"function": "root:demo@0.1.0::index.mq.md::力学.计算力"
} }
``` ```
| Field | Semantics | | Field | Requirement |
|---|---| |---|---|
| `id` | `<module_id>#resource:<kind>-<n>`; `n` is the 1-based ordinal among resources of that kind in the module, in document order | | `id` | Canonical unit id. Display escapes `/`, `#` and `%` inside each path segment as `%2F`, `%23`, `%25`; `path` is the authoritative structure and consumers must not split `id`. |
| `module_id` | redundant with the enclosing module, present for flattened consumers | | `path` | Canonical NFC/whitespace-normalised heading path, including this heading; `[]` for the root. |
| `unit_id` | innermost owning unit | | `parent_id` | Root: `null`. Non-root: nearest real ancestor unit, `null` only for the root; not the Markdown DOM parent. |
| `kind` | `formula` or `code`; future kinds are additive and unknown kinds must be ignored | | `kind` | `root`, `namespace` (H1), `function` (Exec H2), `knowledge` (Knowledge H2), `section` (H3-H6). |
| `span` | Markdown node byte span, including math delimiters/fence, relative to that module's source | | `name` | Normalised heading name; `""` for the root. |
| `content_digest` | SHA-256 of the payload: formula LaTeX bytes without delimiters; exact code fence source bytes | | `level` | 0 for the root, otherwise 1-6. |
| `language` | code fence info string (may be `""`); `null` for formulas | | `mode` | Effective `exec` or `knowledge`; the root is `knowledge`. |
| `display` | formula only: block vs inline math | | `mode_origin` | Root: `default`. Non-root: `explicit` when the ATX heading declares `@exec`/`@knowledge`; otherwise `inherited`. Setext headings never declare. |
| `mode_source_unit_id` | The unit that provides the effective mode: the root, or the nearest explicit ancestor (possibly the unit itself). Must be the unit or one of its ancestors. |
| `heading_span` | Root: `null`. Otherwise the original heading AST span. |
| `span` | Root: whole source including BOM. Otherwise the complete section range: from the heading start to the next heading of the same or higher level, or EOF; it includes all child headings and excludes the next sibling. |
| `function` | Canonical owning `FunctionId` for an Exec section; `null` for Knowledge/namespace/root. Only an Exec H2 creates a callable; nested sections point at it. |
Resource ids are Analysis-local ordinals, not persistent symbols and not `ref` Mode declarations are only the ATX first-Text-child `@exec`/`@knowledge`
anchors. Content identity is `(module_id, content_digest)`; location identity is tokens; any other `@word` is `sem.invalid_mode_marker`. Mode inheritance pops
`(module_id, span)`. Inserting an earlier resource renumbers later ordinals, but same-or-higher-level ancestors first, so a sibling never supplies a mode.
the content digest and span still let a consumer detect the change. Payloads Headings inside lists, block quotes or fences do not create language units.
are not copied into Analysis: consumers read the module source (via
`relative_path`) and slice `span` or verify `content_digest`.
## 5. Diagnostics ### 3.3 Anchors
Diagnostics no longer embed absolute physical paths: ```json
{"anchor": "计算力", "unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力"}
```
`anchors` projects the single `UnitIndex.anchors` map, sorted by `anchor`.
Anchors are navigation names, not identities; slug collisions use the current
numbered algorithm. A display title, semantic name, anchor and unit id are
different concepts; the display title comes from the AST.
### 3.4 Functions
```json ```json
{ {
"module": "root:res@0.1.0::index.mq.md", "id": "root:demo@0.1.0::index.mq.md::力学.计算力",
"unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力",
"local_name": "计算力",
"namespace": "力学",
"span": {"start": 10, "end": 90},
"heading_span": {"start": 10, "end": 30},
"signature": {
"kind": "explicit",
"params": [{"name": "n", "required": true, "type": "Int", "default": null,
"span": {"start": 31, "end": 41}}]
},
"effects": ["unknown"],
"body": []
}
```
Every function corresponds one-to-one to an Exec H2 and to its `function` unit.
`namespace` is `null` outside an H1 namespace. Parameters keep declaration order
for explicit signatures and the canonical order for inferred ones; spans are
projected as written. `effects` is the honest conservative default
`["unknown"]`, never a purity proof.
`body` supports every current public statement: `assign` (string local target or
`{"kind":"index",...}`), `expression`, `branch` (ordered arms), `loop`,
`return`, `break` and `continue`, with the expression variants `literal`,
`variable`, `list`, `record`, `unary`, `binary`, `member`, `index`, `call`.
Arbitrary-precision integers are decimal strings; a float is a finite JSON
number. An unknown required kind is rejected by schema/semantic validation, not
silently dropped.
### 3.5 Imports
`imports` keeps `{alias, target, span, resolved}` in document order.
`resolved` is the canonical target module id from the single prepared import
resolution, or `null` for a diagnostic import. Imports are explicit; a link is
never an import.
### 3.6 References
See §5.
### 3.7 Calls
```json
{
"function": "root:demo@0.1.0::index.mq.md::main",
"span": {"start": 40, "end": 52},
"callee": {"kind": "ident", "name": "计算力"},
"state": "function",
"target": "root:demo@0.1.0::index.mq.md::力学.计算力",
"target_kind": "function",
"target_owner": null,
"reason": null
}
```
Calls are projected from the single prepared `CallBindingTable`, one record per
call expression occurrence, in source order. `state`:
| State | `target` | `target_kind` |
|---|---|---|
| `function` | existing canonical `FunctionId` | `function` |
| `builtin` | canonical builtin name | `builtin` |
| `plugin` | full dotted export name | `plugin` |
| `unresolved` | `null` | `null` |
For `plugin`, `target_owner` is
`{"kind":"plugin","package":"<package>","digest":"sha256:<64 hex>"}` from the
static descriptor; no plugin function node is fabricated. `reason` is
`dynamic` for a value call and `unbound` when preparation could not bind a
statically known callee, otherwise `null`. Legal dynamic calls do not
invalidate Analysis; genuine compile errors do.
### 3.8 Resources
`resources` projects exactly the inert `marqdo-ir::Resource` kinds `formula` and
`code`: `id` (module-local ordinal), `module_id`, `unit_id`, `kind`, `span`,
`content_digest`, `language` (`null` for formula), `display` (`true|false` for
formula, `null` for code). The payload lives in `source`, not in the artifact.
Ordinals are snapshot-local, never persistent symbols.
## 4. Diagnostics
```json
{
"module": "root:demo@0.1.0::index.mq.md",
"relative_path": "index.mq.md", "relative_path": "index.mq.md",
"span": {"start": 10, "end": 20}, "span": {"start": 10, "end": 20},
"line": 2, "line": 2,
"column": 3, "column": 3,
"severity": "warning", "severity": "error",
"code": "sem.inferred_signature", "code": "sem.invalid_mode_marker",
"message": "...", "message": "...",
"hints": [] "hints": []
} }
``` ```
`span` is the primary coordinate; `line`/`column` are presentation-derived from `span` is primary; `line`/`column` are 1-based presentation derived from the
the owning module. `span`, `line` or `column` may be `null` when no precise owning module and may be `null`. A successful Analysis contains no `error`
location exists. diagnostic. Diagnostics are deterministic: source position, then code.
The `code` value is an open, stable string: the current language revision adds ## 5. Reference resolution
the `sem.*` family (`spec/mapping.md` §8) and removes the old
`markdown.inert_executable` warning. Diagnostic codes may be added without changing the structure.
## 6. Loop transfers One pure resolver (`crates/cli/src/document_refs.rs`) handles every Markdown
link. It takes the source module, source span, raw URL and an explicit catalog
of documents with anchors and exact names. It performs no load, call binding,
import, network access or caller-entry fallback.
Conditional arms appear in source order. Both `break` and `continue` are ### 5.1 Catalog scope
statements with a `kind` and the half-open UTF-8 `span` of their carrier.
They have no operands or call edges. Walk the enclosing bodies to find
the nearest loop. `break` transfers past that loop and `continue` transfers
to its condition.
## 7. Validation * Ordinary Analysis uses only the modules already loaded for this program.
A local target outside that set is `not_loaded`; the artifact states that the
current scope did not verify it, never that it is absent.
* `check --refs` and `inspect --refs` build an explicit extension catalog:
direct local `.mq.md` targets are read once and parsed with the same heading
index; plain files are checked for existence only. They are not added to
`modules`, imports, call bindings or the program, and are never executed.
Budget/IO failures produce errors, never a silent downgrade.
* Given the same catalog, Analysis, `check` and `inspect` must produce the same
state for the same link.
Require exactly `schema: "marqdo.analysis"` and `schema_version: 3` before ### 5.2 Reference record
traversing the document. The [JSON Schema](schemas/analysis.schema.json)
validates record shapes. Check source digests, spans, ownership and
reference targets separately. Its full branch and loop structure applies
equally to simple projects and imported modules.
Source digests cover the original bytes. Preserve UTF-8 byte offsets for ```json
BOM, CRLF, CJK and emoji. Observation binds to the SHA-256 of the exact {
emitted Analysis JSON bytes. "source": "root:demo@0.1.0::index.mq.md",
"source_unit": "root:demo@0.1.0::index.mq.md#力学",
"url": "./theory.mq.md#formula",
"span": {"start": 20, "end": 50},
"state": "not_loaded",
"target_kind": null,
"target_module": null,
"target_unit": null,
"candidate_package_instance_id": "root:demo@0.1.0",
"candidate_path": "theory.mq.md",
"fragment": "formula",
"candidates": []
}
```
`source_unit` is the innermost unit whose complete `span` contains the link.
`candidate_path` is the normalised package-relative logical candidate; no OS
path is emitted. `fragment` is the once-decoded fragment or `null`; the raw
`url` is always preserved. `candidates` contains exact unit ids only for an
ambiguous canonical-name fallback.
| State | Meaning | Constraints |
|---|---|---|
| `resolved` | exact target in this catalog, or an explicitly verified local file | `target_kind: module` requires `target_module`; no fragment means `target_unit: null`; a verified plain file uses `target_kind: file` and needs no module |
| `not_loaded` | local candidate is outside this catalog; existence unverified | `target_unit: null`; never reported as missing |
| `missing` | catalog module has no such fragment, or explicit verification proved the file absent | keep the known `target_module` when available |
| `ambiguous` | canonical-name fallback has two or more exact candidates | `target_unit: null`; `candidates` lists all |
| `external` | URI has an external scheme (`http`, `https`, `mailto`, ...) | no network access; target fields `null`; not an error |
| `outside_scope` | local target escapes the allowed package root, or uses an absolute/file/drive/UNC path | target unread; no physical path emitted |
| `invalid` | malformed URI/percent encoding or unsupported address | no guessed repair |
Exact anchor lookup comes first; the existing canonical-name fallback (if
retained) collects all exact name candidates: 0 `missing`, 1 `resolved`, 2+
`ambiguous`. No `.find()`, case folding, edit distance or fuzzy binding. An
empty fragment is the document root. The fragment is percent-decoded exactly
once; invalid sequences are `invalid`.
Consumers may not reinterpret a non-`.mq.md` target as a Marqdo module. A
regular Markdown fragment is not verified against a foreign document profile:
the state is `not_loaded` with a diagnostic that coverage was insufficient, not
`missing`.
### 5.3 Security
Paths are normalised segment-by-segment after one percent decode. `file:`
URIs, OS absolute paths, drive/UNC paths, NUL, symlink escape and encoded
traversal are rejected or `outside_scope`. A legal `../` is allowed only while
the normalised candidate stays inside the package module root. The ordinary
Analysis opens no candidate. `--refs` opens only allowed local files, with
size/count limits, conservative symlink rejection and canonical root checking.
## 6. Validation
There are two steps on one boundary:
1. the [JSON Schema](schemas/analysis.schema.json) validates closed record
shapes, required fields, enums, types and array element shapes;
2. a semantic validator checks cross-record invariants that JSON Schema cannot
express.
The required semantic invariants are:
1. schema/revision/profile/entry/root/package/module identities agree; ids are
unique; paths do not escape their package; text is valid UTF-8.
2. every `source_digest` matches its `source`; every span belongs to that
module's source, has `start <= end <= source.len()` and lies on UTF-8
boundaries; functions, statements, resources and references never point at
another module.
3. there is exactly one root unit; parent edges form a tree (no cycle); each
`path` equals its parent's path plus its name; full spans nest with their
parent; heading AST, unit, function and anchor links exist and are
unambiguous; mode source units are self-or-ancestor.
4. functions are unique and correspond to Exec H2 units; each `function` field
points at the real definition; resolved call targets exist; builtin/plugin
targets never pretend to be Marqdo functions; imports resolve to catalog
modules.
5. reference state/nullability/candidates are consistent; `resolved` targets
exist in the catalog; ordinary Analysis has no fabricated external module;
resources refer to real units and their digests match the AST payload.
6. diagnostic owner/severity/code/span/line/column are valid; a successful
Analysis has no error; all arrays and modules are deterministically sorted.
The producer runs typed local checks before encoding; the independent
`tests/consumers/analysis_consumer.py` and `validate_protocols.py` validate the
serialized bytes. Production validation never replaces consumer validation of
untrusted input.
## 7. Failure and exit semantics
`check` keeps its CLI contract: success `0`; static diagnostic errors `1`;
argument, load/IO or output failures `2`. `--json` is a check diagnostic
summary, not a second Analysis writer. `--emit` is the only full Analysis
writer.
A failed check publishes no success artifact. It may remove a previous artifact
at the caller-specified output path only when that path is not an input source,
manifest, lock/dependency file, directory, symlink or hard link to one, and only
when that previous artifact is the one the caller named. Partial/unsuccessful
Analysis documents do not exist.
## 8. Output safety
`--emit PATH`:
* refuses a path equal to any loaded source, the manifest or the lock file,
including through a hard link or symlink;
* refuses a directory, a symlink at the destination, or an output whose parent
cannot be created safely;
* creates the temporary file exclusively with owner-only permissions on Unix,
writes and flushes it, then renames it over the destination;
* on failure removes only its own temporary file and leaves inputs untouched;
* uses the same canonical encoder for the file and for the Observation digest.
No second pretty writer is allowed.
## 9. Observation binding
`run`/`call` compute `source.analysis_digest` by encoding the same
`PreparedProgram` with the same encoder and hashing the exact bytes.
Observation never copies `source`, document AST or link targets into runtime
events. A run with different static options (for example `--refs`, `--plugin`
or a different entry) binds a different artifact; consumers must re-check
digests against the disk version they rely on.
+5 -1
View File
@@ -80,7 +80,11 @@ parses it exactly once with `serde_yaml`. Supported semantics:
## 5. AST view ## 5. AST view
`marqdo inspect --ast --json` prints this tree: `marqdo inspect --ast --json` prints this tree, and `marqdo check --emit`
projects the identical `modules[].document` shape with the same projector
(`spec/analysis.md` §3.1). Neither is a second parser or a second long-lived
AST. The root `document` span covers the whole source including a BOM; every
span is a half-open UTF-8 byte offset into `modules[].source`.
```json ```json
{ {
+4
View File
@@ -39,6 +39,10 @@ fields. Reject other format identifiers, unknown kinds and invalid payloads.
SHA-256 over the file bytes, including formatting. Before highlighting a SHA-256 over the file bytes, including formatting. Before highlighting a
source span, validate the binding, module source digest and original UTF-8 source span, validate the binding, module source digest and original UTF-8
half-open byte range. A changed source or Analysis invalidates attribution. half-open byte range. A changed source or Analysis invalidates attribution.
The static options that change the projection include the entry, `--plugin`,
load/extension selection and diagnostics; a `--refs` check adds diagnostics
and therefore emits different bytes. Run/call never copy `source`, the
document AST or link targets into runtime events; they only bind the digest.
- `call.enter` identifies the call instance and its parent. `call.exit` - `call.enter` identifies the call instance and its parent. `call.exit`
closes that same instance. Call carriers belong to the caller module. closes that same instance. Call carriers belong to the caller module.
Parameter spans identify declarations in the called module. Parameter spans identify declarations in the called module.
+14 -2
View File
@@ -16,7 +16,7 @@ Normative implementation:
| Resource collection and attribution | `crates/marqdo-frontend/src/resources.rs` | | Resource collection and attribution | `crates/marqdo-frontend/src/resources.rs` |
| Executable payload → statement mapping | `crates/marqdo-frontend/src/map.rs` | | Executable payload → statement mapping | `crates/marqdo-frontend/src/map.rs` |
| `ref(...)` runtime resolution | `crates/marqdo-runtime/src/builtins_impl.rs` | | `ref(...)` runtime resolution | `crates/marqdo-runtime/src/builtins_impl.rs` |
| Static link graph (`inspect --refs`) | `crates/cli/src/commands.rs` | | Static link graph (Analysis `references`, `check --refs`, `inspect --refs`) | `crates/cli/src/document_refs.rs` |
| Cross-module call validation | `crates/marqdo-frontend/src/calls.rs` | | Cross-module call validation | `crates/marqdo-frontend/src/calls.rs` |
This file complements [`mapping.md`](mapping.md) (AST roles) and This file complements [`mapping.md`](mapping.md) (AST roles) and
@@ -89,7 +89,10 @@ pub struct UnitId { pub module: ModuleId, pub path: Vec<String> }
normalization. `## @exec main` has the semantic name `main`; the declaration normalization. `## @exec main` has the semantic name `main`; the declaration
is never part of a `UnitId`, `FunctionId` or anchor. is never part of a `UnitId`, `FunctionId` or anchor.
* `Display` renders `<module>#<path joined by '/'>`; the root unit renders as * `Display` renders `<module>#<path joined by '/'>`; the root unit renders as
`<module>#`. `<module>#`. A path segment escapes `%`, `/` and `#` as `%25`, `%2F` and
`%23`, so a single segment named `a/b` cannot collide with the two-level path
`a` -> `b`. Consumers must use the structured `UnitId.path` exposed by
Analysis and must never split a display id to recover hierarchy.
* `UnitKind` is `root`, `namespace` (`#`), `function` (`##` Exec) or `section` * `UnitKind` is `root`, `namespace` (`#`), `function` (`##` Exec) or `section`
(`###`+). A Knowledge H2 is an addressable knowledge unit, not a `function`. (`###`+). A Knowledge H2 is an addressable knowledge unit, not a `function`.
Sections are addressable but not callable. Sections are addressable but not callable.
@@ -125,6 +128,15 @@ to units (`crates/marqdo-frontend/src/units.rs::github_slug`):
Internal ids stay canonical, so a heading rename is a link-breaking change Internal ids stay canonical, so a heading rename is a link-breaking change
but never changes the canonical unit path. but never changes the canonical unit path.
## 2.5 One document-link resolver
Analysis `references`, `check --refs` and `inspect --refs` use one pure
resolver over an explicit catalog (`spec/analysis.md` §5). It never loads a
module, binds a call or accesses the network. Ordinary Analysis uses only the
loaded modules; the `--refs` checks may add directly referenced local files to
a separate catalog for existence/anchor verification. The retired
`commands.rs::resolve_link` algorithm does not exist.
## 3. Front matter imports ## 3. Front matter imports
Imports exist only as an explicit YAML mapping in the document's front matter Imports exist only as an explicit YAML mapping in the document's front matter
File diff suppressed because it is too large. Load diff