Files
marqdo-cli/spec/document-structure.md
cflmy 0f87f856db
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was canceled
feat: add offline environment report and document-structure contract
Implements the two CLI-owned P0 sub-issues of the ecosystem architecture
tickets without adding document-language syntax.

Environment report (marqdo-cli#26 §9.2, binding for #20):
- `marqdo inspect --environment [--json]` emits `marqdo.environment` v1:
  producer version and build-embedded source commit, platform/arch/glibc and
  real strict probe, adjacent provider-worker version/SHA (offline
  `--build-info`, bounded), verified Bundle identity, current protocol
  revisions and path-free diagnostics. Project-independent, offline, and
  exclusive with document inspection flags.
- Release builds embed `MARQDO_BUILD_SOURCE_SHA`; the CI `build` lane sets it.
  `tools/release/package.py` refuses to stage an archive whose binaries report
  another commit or Bundle digest, and `tools/release/smoke.py` re-verifies the
  extracted archive.
- Spec: `spec/environment.md`. Tests: `environment_report.rs` (5 cases) and
  in-module unit tests; docs/releasing/COMPATIBILITY/STATUS updated.

Document-structure contract (marqdo-cli#25):
- `spec/document-structure.md` states the current author/tool semantics once:
  heading mode inheritance (nearest ancestor, only Exec H2 callable), unit
  identity and duplicate-name rules, anchor collision numbering, byte-exact
  half-open spans, `index.mq.md` entry vs directory-dependency import meaning,
  link != import != call, Proposed annotations marked not implemented, and the
  Analysis fields consumers may rely on. It links the single authoritative
  specs instead of duplicating them.
- Tests: `document_structure.rs` (6 cases) + docs_consistency coverage.

No runtime behavior change, no new language surface, no new cross-repo
dependency. `docs_consistency` and `architecture_boundaries` remain green.
2026-11-30 11:35:24 +08:00

192 lines
11 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Marqdo Document Structure and Entry Semantics
This is the author/tool-facing overview of **what a `.mq.md` document is** and
**how a document becomes a program**: heading modes, unit identity, anchors,
spans, `index.mq.md` entry meaning, and the three document relations (link,
import, call). It states only semantics that are implemented today.
Normative detail lives in one place per fact: syntax and the Markdown→program
mapping are
[`mapping.md`](mapping.md) / [`../docs/architecture/RFC-LANG-0002-unified-semantics.md`](../docs/architecture/RFC-LANG-0002-unified-semantics.md);
the public static projection is [`analysis.md`](analysis.md); link/reference
resolution is [`references.md`](references.md); package and entry resolution is
[`package-format.md`](package-format.md) plus [`references.md`](references.md)
§3.1. This document links those facts for readers and states the consumer
stability contract; it does not create a second specification.
## 1. Document root and heading modes
A document is one CommonMark/GFM AST. Headings are sibling blocks, so scopes
are derived from heading levels, never from container nesting.
| Heading | `kind` | Callable? | Notes |
|---|---|---|---|
| (document root) | `root` | no | Mode `knowledge`, level `0`, path `[]`. |
| H1 | `namespace` | no | Namespace for nested functions. |
| H2 with `@exec` | `function` | **yes** | The only callable document unit. |
| H2 with `@knowledge` | `knowledge` | no | Inert knowledge section. |
| H3–H6 | `section` | no | Section of the enclosing unit; never callable. |
Rules (implemented by `marqdo-frontend`):
* The **document root is Knowledge**. A document with no mode marker still has
a knowledge root and cannot be called.
* Only ATX headings may declare `@exec`/`@knowledge`; Setext headings never
declare. The marker must be the heading's first `Text` child; any other
`@word` marker is the hard error `sem.invalid_mode_marker` (there is no
per-file mode or second selector).
* A heading without a marker **inherits the nearest ancestor's effective
mode**, never a sibling's. Inheritance pops same-or-higher-level ancestors
first, which is why a `###` section under an Exec H2 is Exec while the next
`##` sibling under a Knowledge H1 is Knowledge.
* Only a level-2 Exec heading creates a `FunctionId`. A section inside it
reports the owning function; a section outside one has no function.
* Executable payloads outside an owning Exec H2 are
`sem.exec_without_function`. Prose is inert everywhere.
* Headings inside lists, block quotes or fenced code do not create units.
* Mode declarations are not a navigation feature: adding `@knowledge`/`@exec`
declares meaning, it does not select a different parser or execution path.
Heading annotations (`{#id}`-style) are **Proposed** in
[`heading-annotations-v1.md`](heading-annotations-v1.md) and are not current
capability: the CLI currently rejects unknown `@` markers with
`sem.invalid_mode_marker`. Do not build tools on the proposal.
## 2. Units, identity, anchors and spans
A heading that participates in the language creates an addressable **unit**.
The root is always `units[0]`; all units are in document order.
* `id` is the canonical identity and may contain escapes for `/`, `#` and `%`.
`path` is the authoritative structural name; consumers must not split `id`
into segments.
* `parent_id` is the nearest real ancestor unit (not the Markdown DOM parent).
* Two headings with the same canonical name in the **same scope** are a hard
error (`sem.duplicate_unit_name`); they are not auto-suffixed. The same name
under different parents is allowed and addressable by `path`/`id`.
* `anchors` is a separate namespace of navigation names derived from heading
text with the GitHub-style slug algorithm. Slug collisions get the numbered
suffix `-2`, `-3`, … in document order. An anchor is a navigation name, not
an identity: resolve it to `unit_id`, never to a function or execution right.
* `heading_span` is the original heading AST span. `span` is the complete
section range: from the heading start through the next heading of the same or
higher level, or EOF; it includes child headings and excludes the next
sibling. The root `span` covers the whole source including a BOM.
* All spans are **half-open UTF-8 byte offsets** into `modules[].source`.
Slicing `source.as_bytes()[span.start..span.end]` is exact, including for a
BOM, CRLF line endings, combining characters, a missing trailing newline and
multi-byte text. `analyze`/`check --emit` and `check --refs` are different
projections; bind a digest when mixing artifacts (see `analysis.md` §1).
## 3. `index.mq.md` and entry semantics
`index.mq.md` is an **ordinary `.mq.md` document**. The file name is a
convention, not a language keyword and not a second document type.
* The **project entry** is the file passed to `check`/`run`/`call`/`inspect`.
Analysis records it as `project.entry_module_id`; it must occur exactly once
in `modules`. A second entry of the same project gets its own Analysis and is
never merged by basename.
* `marqdo init` generates a starter `index.mq.md`. That is a project template
choice, not execution semantics.
* A **path dependency** whose `marqdo.yaml` `path:` names a directory resolves
to `<directory>/index.mq.md` when the dependency is imported; the loaded
module keeps the dependency's package instance identity
(`dep:<name>@<version>[#<digest>]::index.mq.md`). That is import resolution,
not "the project entry is whatever index file is nearby".
* Nothing scans directories, auto-loads `index.mq.md`, or treats a directory
link as an import. Imports come only from the explicit YAML front matter.
* An `index.mq.md` used as navigation content does not change execution. Any
`@exec` H2 in it is a normal callable function with normal capability rules;
links inside it are static references only.
* Unresolved imports/missing modules are diagnostics (`module.unresolved`,
`ref.*`); there is no fuzzy search or basename fallback. See
[`references.md`](references.md) §3 and §5.
## 4. Three relations: link, import, call
The three must not be conflated; none is inferred from another.
| Relation | Syntax | Effect | Public projection |
|---|---|---|---|
| **Link** | Markdown `[text](url)` / image | Static reference only. Never loads a module, never imports, never grants read/execute. | `modules[].references[]` with state `resolved`, `not_loaded`, `missing`, `ambiguous`, `external`, `outside_scope` or `invalid`. |
| **Import** | YAML front matter `import: {alias: target}` in a module | Loads exactly the named module (`@dependency`, `std:<relative>` or relative path). Explicit, depth-first, no directory scan. | `modules[].imports[]` with `resolved` module id or `null` for a diagnostic import. |
| **Call** | Expression inside an executable payload | Binds statically to one callable; runs only under `run`/`call` with capability authorization. | `modules[].calls[]` with state `function`, `builtin`, `plugin` or `unresolved`. |
Partition rules:
* A link **never** imports or executes. A document may link to a module it did
not import; ordinary Analysis reports its state honestly (`not_loaded` when
the catalog did not verify existence), and `check --refs` verifies local
files without adding them to the program.
* `ref("#anchor")` returns a static `Formula | Code | FunctionRef` handle; it
does not read a section body and does not grant execution.
* Only an Exec H2 function can be called; calling a knowledge unit, namespace,
section or plain Markdown heading is not part of the language.
* Dynamic (`unresolved`/`dynamic`) calls are legal runtime values; they do not
become a second binding table.
## 5. Authoring guidance (not a CLI enforcement layer)
`marqdo#55` defines repository-level documentation expectations (project
entry, navigation, minimum per-document purpose). The CLI does **not** enforce
those editorial rules: Markdown structure checks belong to `marqdo-lint`, and
navigation/index policy belongs to the consumer repository. A `.mq.md` document
must be independently meaningful to a human reader; adding a new document or a
new knowledge file must not require new CLI syntax.
## 6. Not supported / deferred
* Heading annotations (`heading-annotations-v1.md`, Proposed) and any
`{#id}`/attribute syntax.
* AI-specific metadata, decorators, sidecar indexes or a second document
format.
* Automatic execution of prose or knowledge paragraphs, or "execute this
section" navigation commands.
* A second mode selector (`map_v1`, `--legacy`, per-file syntax switch) or
compatibility fallback for retired syntax.
* Implicit imports from links, file names or directory scans; directory-based
project entry inference.
* Anchor-based execution rights: an anchor resolves to a unit identity only.
## 7. Consumer stability contract
Tools may rely on the following public projection without reading CLI source.
Changes require an Analysis schema/ADR change and consumer updates; there is
no private-structure dependency.
| Fact | Field | Stability |
|---|---|---|
| Project entry | `project.entry_module_id`, `project.root_id`, `project.identity_kind` | Stable. |
| Module identity | `modules[].id`, `package_instance_id`, `relative_path`, `source_digest`, `source` | Stable; bind `AnalysisDigest` when mixing projections. |
| Heading tree | `units[].id/path/parent_id/kind/name/level`, document order, root first | Stable. |
| Modes | `units[].mode`, `mode_origin`, `mode_source_unit_id`, `function` | Stable. |
| Navigation | `units[].heading_span/span`, `anchors[]` | Stable; byte offsets. |
| Relations | `imports[].resolved`, `references[]` states, `calls[]` states/targets | Stable vocabulary; see `analysis.md` §5–§7. |
| Inert payloads | `resources[]` `formula`/`code` kinds | Stable. |
A consumer that needs a structural fact not in that table must request an
Analysis field through the schema process; it must not parse Markdown or IR
privately. Lint/Knowledge/AI consumers specifically may depend on: entry module
identity, heading tree, mode/mode_source, anchors, exact spans, import/call
separation and reference states.
## 8. Contract tests
| Test | Asserts |
|---|---|
| `crates/cli/tests/document_structure.rs` | heading modes/inheritance, same-name scope rules, anchor collision numbering, byte-exact spans with BOM/CRLF/no-final-newline, `index.mq.md` entry and directory-dependency resolution, link≠import≠call, invalid `@word` rejection. |
| `crates/cli/tests/heading_inheritance.rs` | sibling/ancestor inheritance through real `check`/`run`/`call`. |
| `crates/cli/tests/conformance_semantics.rs` | mapping and diagnostics for unit/heading semantics. |
| `crates/cli/tests/analysis_boundary.rs` | Analysis v3 shape and consumer validation. |
## 9. Change rules
* New document-language semantics require a language ADR plus `spec/mapping.md`
and `RFC-LANG-0002` updates; a tool requirement alone is not a reason to add
syntax (`marqdo#55` §13.4).
* A new Analysis field requires an `analysis.md`/schema change and a consumer
candidate on the same contract; no private projection is exposed.
* No second document-structure specification is maintained here or in Lint,
Knowledge, AI or the parent repository. This page links the single sources.