docs(m0.6): integrate plan and freeze R0 baseline decisions

- move the revision package into docs/ and spec/, preserving all content
- record the M0.6 plan/audit cross-references and Proposed status
- correct stale STATUS claims about CI, console capability and check --refs
- add Accepted ADRs 0008-0012 for package identity, callable resolution,
  plugin export routing, capability broker and kernel providers
- record the passing R0 baseline gate (fmt, clippy, workspace tests)
This commit is contained in:
cflmy committed 2026-11-20 11:34:45 +08:00
1 parent 0116160399
commit 66476fbbfb
13 files changed
+1759 -12

No files matched your search

@@ -0,0 +1,164 @@
# ADR-0008: Package-aware module identity and source resolution
Status: **Accepted**
Date: 2026-11-20
Supersedes: the path-only `ModuleId` interpretation used by the M0.5 loader
## Context
M0.5 identifies a module by its project-root-relative path
(`crates/marqdo-ir/src/lib.rs::ModuleId`). The loader canonicalises every file
and rejects anything outside the project root. This works for one project but
cannot represent:
* two locked versions of the same dependency at once;
* a dependency installed in a shared, content-addressed cache rather than below
the importing project;
* a dependency whose physical cache directory moves without changing meaning;
* stable function/knowledge identities for Analysis v1.
The M0.6 plan (`docs/NEXT_PHASE_IMPLEMENTATION.md` §1A E06/E07, R1) makes this
the first architectural correction because Analysis v1 must not freeze a
physical-path identity.
## Decision
### 1. Module identity is logical
`marqdo_ir::ModuleId` becomes:
```rust
pub struct PackageInstanceId(pub String);
pub struct ModuleId {
pub instance: PackageInstanceId,
pub relative_path: String,
}
```
The canonical display/encoding is `<instance>::<relative_path>` with `/`
separators. A string without `::` is accepted only as a convenience for tests
and standalone documents and is interpreted as `root:default`.
`PackageInstanceId` is one of:
* `root:<project-name>@<version>` for a project entry package;
* `root:default` when no `marqdo.yaml` exists;
* `dep:<package-name>@<version>#<content-digest-prefix>` for a dependency
instance.
The dependency suffix is derived from the locked content digest, not from the
cache directory. Moving a cache or copying a dependency therefore does not
change identity, while two different locked versions (or two different contents)
do. A dependency without its own manifest uses version `0.0.0` and its manifest
alias as the package name.
Physical paths remain available for diagnostics and IO, but they are not part
of `ModuleId`, `FunctionId` or `UnitId`.
### 2. Package resolution is a package-layer concern
`marqdo-package` exposes:
```rust
pub enum PackageOrigin {
Root,
Path { declared: PathBuf },
Git { url: String, rev: String },
}
pub struct ResolvedPackage {
pub instance_id: PackageInstanceId,
pub name: String,
pub version: String,
pub origin: PackageOrigin,
pub revision: Option<String>,
pub content_digest: Option<String>,
pub module_root: PathBuf,
pub manifest: Option<Manifest>,
}
pub struct PackageResolver { /* project root + manifest + lock */ }
impl PackageResolver {
pub fn resolve_entry(&self, entry: &Path) -> Result<ResolvedPackage, String>;
pub fn resolve_alias(&self, alias: &str) -> Result<ResolvedPackage, String>;
}
```
The loader consumes `ResolvedPackage` and never branches on `path`/`git`
itself. Source kinds are implemented by the package crate: path dependencies in
R1, pinned Git revisions in R5. Additional sources (registry mirrors, vendor
directories) must implement the same interface rather than adding loader
conditions.
### 3. Import forms remain explicit
A front-matter import is still either:
* `./relative/file.mq.md` inside the current package; or
* `@alias` naming a manifest dependency.
No implicit searching, no PATH-like resolution and no network access while
checking. Markdown links remain static references, not imports.
### 4. Lock format v2
`marqdo.lock` becomes `lock_version: 2`. Each package entry records:
```yaml
- name: geometry
instance_id: "dep:geometry@0.1.0#0123456789ab"
source: "path:./packages/geometry"
sha256: "<content digest>"
```
Readers accept v1 by deriving the instance id from the source + `sha256` (or
`dep:<name>@0.0.0#unlocked` when no digest exists); writers always emit v2.
`sync --locked` compares instance ids and digests, so a source or content change
fails rather than silently selecting the newest package.
## Alternatives
1. Keep path-only `ModuleId` and add a separate package id only in Analysis.
Rejected: the public protocol would still expose physical identity and the
runtime would not distinguish two versions.
2. Put the cache path in the instance id. Rejected: cache relocation changes
identity and defeats reproducible knowledge/proof artifacts.
3. Encode source kind (`path`/`git`) in `ModuleId`. Rejected: the same logical
package may later be served from a lockfile/vendor cache; identity must not
depend on how it was fetched.
4. Require a global registry immediately. Rejected: local path and pinned Git
sources are the M0.6 scope; a registry is a later, optional source.
## Compatibility
This is a deliberate 0.x breaking change (M0.6). Existing lockfiles are read
through the v1 migration path; old `ModuleId` strings without an instance prefix
are accepted as `root:default`. CLI JSON that previously printed
`index.mq.md` now prints `root:default::index.mq.md` (or
`root:<project>@<version>::index.mq.md`). No released API promised the old form.
## Security
`PackageResolver` remains static: it reads manifests/lockfiles and hashes
content, but never executes package code or install scripts. The loader rejects
paths that do not resolve inside the resolved package's `module_root`. Git
resolution is limited to an exact revision and is performed without running
repository hooks (`GIT_TERMINAL_PROMPT=0`, no submodules/install scripts).
## Testing
* package tests for instance-id stability across cache/path moves, v1 lock
migration and source mismatch;
* loader tests for two versions of the same dependency, path traversal
rejection and canonical diagnostics;
* CLI integration tests that move a path dependency and assert unchanged
`ModuleId`/analysis output.
## Migration & rollout
R1 implements path sources and the new `ModuleId`; R5 adds pinned Git and
environment materialisation. `docs/STATUS.md` and `spec/references.md` are
updated in the same change. Analysis v1 (R4) is frozen only after this ADR is
implemented and its tests pass.
@@ -0,0 +1,148 @@
# ADR-0009: One callable resolver for builtins, Marqdo functions and ABI exports
Status: **Accepted**
Date: 2026-11-20
## Context
M0.5 resolves calls in three unrelated places:
* `crates/marqdo-ir/src/builtins.rs::BUILTINS` plus
`crates/marqdo-frontend/src/calls.rs` for static validation;
* `crates/marqdo-runtime/src/builtins_impl.rs::dispatch` for builtin execution;
* `crates/marqdo-runtime/src/interpreter.rs` for Marqdo function lookup, with an
ad-hoc fallback that sends any unknown `alias.name` member call to the host as
a trusted plugin call.
Adding one external function therefore risks touching the builtin table, the
frontend, the runtime and the host. The frontend cannot statically validate a
plugin call because it has no descriptor for the export, and the runtime decides
by "first builtin/function/plugin that matches".
M0.6 R1/R2 require a single static description and a single runtime binding
path. The language expression grammar and control flow remain fixed; only the
symbol layer becomes registry-driven.
## Decision
### 1. Descriptor
`marqdo-ir::callable` defines:
```rust
pub struct CallableId(pub String); // canonical, globally unique
pub enum CallableOrigin {
Builtin,
Marqdo, // a FunctionId
AbiPlugin { package: String, export: String },
}
pub struct CallableDescriptor {
pub id: CallableId,
pub public_name: String, // `print`, `数学.阶乘`, `solver.add`
pub owner_package: PackageInstanceId,
pub signature: CallableSignature,
pub effects_requested: Vec<String>,
pub origin: CallableOrigin,
pub implementation_digest: Option<String>,
pub source_span: Option<Span>,
}
pub struct CallableSignature {
pub params: Vec<Param>,
pub kind: SignatureKind,
pub result: Option<String>,
}
```
Builtins keep their static `BUILTINS` table: they are part of the language, not
an extension point. The table is wrapped in descriptors; it is not copied into
every plugin.
### 2. Resolution
`CallableRegistry` is built deterministically from:
1. builtin descriptors (fixed, reserved names);
2. all program functions (canonical and unique local names);
3. explicitly declared external descriptors supplied by the CLI/package layer
from plugin manifests (never by loading a dynamic library during `check`).
Rules:
* fully qualified names are unique; duplicate external names are a hard
conflict, unless the caller explicitly aliases one (`solver.add as add`);
* an unknown function is a compile error, never "try builtins/plugin at
runtime";
* `check` validates arity/parameter names from the static descriptor for every
origin, including ABI exports;
* `run` binds the already-resolved `CallableId` and dispatches by origin;
* `Host` still performs capability authorization at the actual effect, based on
the package/plugin identity and the current execution context.
The existing `BUILTINS` list remains a closed language set. Third-party
extensions never edit it, `calls.rs` match arms or
`builtins_impl.rs::dispatch`.
### 3. Plugin calls
A plugin descriptor is derived from `plugin.yaml` exports
(`name`, `signature`, package, digest). `check --plugin <manifest>` (or a
manifest declared in `marqdo.yaml`) may add these descriptors statically without
loading any shared library. The runtime uses the export's complete dotted name
(`solver.add`), not only the first prefix.
A call form `solver.add(a=1, b=2)` resolves to a `CallableDescriptor` whose
origin is `AbiPlugin`. If no descriptor was declared, it is `symbol.unknown`;
it is not sent to the host speculatively.
### 4. Effects
`effects_requested` is a conservative static summary used for reporting and
permission prompts. It is not proof that an implementation is pure. At
execution the host checks the actual `HostOp` against grants; a manifest cannot
grant itself a capability.
## Alternatives
1. One global dynamic map of strings. Rejected: no static signature, no arity
checks, and unknown names would silently resolve after deployment.
2. Keep three lookup sites and synchronise them by convention. Rejected: the
M0.5 audit (E02) shows they already diverge.
3. Make builtins dynamic too. Rejected: builtins are language semantics and
their list is deliberately closed. Only the resolver is unified.
4. Let `run` probe ABI exports at execution time without a static descriptor.
Rejected: `check` must be able to reject bad calls and must never `dlopen`.
## Compatibility
`BUILTINS`, names and arity stay unchanged. Existing Marqdo function calls keep
working through the registry. Unknown calls that M0.5 treated as plugin calls now
require a declared plugin descriptor; this is a deliberate diagnostic
improvement, not a language change. JSON diagnostics keep stable codes and add
`callable.unknown`/`callable.ambiguous` only where the old code had no specific
answer.
## Security
The registry is metadata, not authority. A descriptor only says "this callable
exists and has this signature"; the host checks `check_plugin`, the package
identity and the current `ExecutionContext` before invoking native code.
`check` must not load a dynamic library, spawn a kernel or execute imported
modules.
## Testing
* frontend tests: builtin/function/plugin descriptors, duplicate qualified
names, aliasing, unknown member calls, arity errors;
* runtime tests: bound `CallableId` dispatch for all three origins;
* CLI contract test: a plugin export's signature is rejected statically before
any library is loaded;
* a plugin with two prefixes exercises both descriptors.
## Migration & rollout
R1 introduces the descriptor/registry and builtin+function resolution. R2 adds
ABI export descriptors, multi-export routing and the capability broker. The
old ad-hoc plugin fallback is removed when the R2 tests prove the replacement.
+111
View File
@@ -0,0 +1,111 @@
# ADR-0010: Register every plugin export by its complete name
Status: **Accepted**
Date: 2026-11-20
## Context
`crates/marqdo-host/src/host.rs::load_plugin` binds one `PluginSlot` using
`manifest.plugin.exports.first()`. The namespace is the text before the first
`.` and `op_plugin_invoke` looks it up with `find(namespace)`. Consequences:
* a plugin exporting `solver.add` and `graph.search` can only be reached through
one of the two prefixes;
* two plugins declaring the same prefix race, and whichever slot was pushed
first wins;
* the frontend has no per-export identity to validate, and a call is effectively
"first namespace match".
The M0.6 audit E03 and plan §10 require complete-name registration for every
export.
## Decision
### 1. Export registration
`StdHost` keeps a registry keyed by the complete export name:
```rust
struct PluginExport {
export: String, // `solver.add`
package: String, // `qdqc.solver`
manifest_digest: String, // sha256 of the canonical manifest/artifact metadata
signature: CallableSignature,
effects: Vec<String>,
plugin: Rc<LoadedPlugin>, // shared by all exports of one loaded library
}
```
Loading a plugin validates the manifest, loads the library **once** and inserts
one entry per export. Insertion is atomic for the whole manifest: if any export
is already registered with a different package/manifest, loading fails and the
previous registry state is unchanged. A re-load of the identical
package+manifest may reuse the existing library.
There is no `exports.first()` and no namespace-only lookup. A call uses the
complete dotted name from `CallableId` / the IR call site.
### 2. Aliases
If two packages intentionally provide the same export name, the user must
declare an explicit alias in the importing manifest/front matter (for example
`solver.add as fast.add`) or the call is ambiguous. M0.6 may implement only the
hard-conflict diagnostic; the alias syntax is additive and must not silently
choose a winner.
### 3. Runtime binding
The frontend resolves `solver.add` to a `CallableDescriptor` (ADR-0009) and the
runtime passes the `CallableId` to the host. The host looks up exactly that id;
it never re-resolves a bare namespace.
The static descriptor must include the manifest/artifact digest so a call
checked against one plugin version is rejected if the installed library changed
between `check` and `run`.
### 4. Worker parity
The isolated worker transport (R2) registers the same complete export names and
the same descriptor table. A plugin's routing must not depend on whether it is
loaded natively or in a worker.
## Alternatives
1. Keep one namespace per plugin and require authors to use one prefix.
Rejected: the manifest already permits multiple namespaced exports and the
audit found silently unreachable functions.
2. Let the host pick the first matching namespace. Rejected: nondeterministic
and spoofable.
3. Reject duplicate export prefixes at manifest validation. Rejected: this
forbids legitimate multi-package ecosystems and does not solve identical
names across different packages.
## Compatibility
Existing single-namespace plugins continue to work; their export is registered
by complete name. Calls that previously relied on "first prefix" behavior now
require the exact export name. No C ABI layout change is needed for native
loading. The host's public `load_plugin` return value becomes a summary of all
registered exports rather than one namespace.
## Security
Registration is not authorization. The manifest digest is recorded so callers
can reject a swapped binary. Capability grants remain per plugin package and are
checked on each invocation (ADR-0011). A conflicting export never replaces an
existing registration.
## Testing
* one plugin with `solver.add` + `graph.search` can call both;
* two plugins exporting `solver.add` produce a deterministic conflict and do not
overwrite;
* a plugin manifest with duplicate export names is rejected during validation;
* a manifest artifact digest mismatch is rejected at load and at call binding;
* worker and native transports expose the same complete-name table.
## Migration & rollout
R2 implements complete-name registration together with the worker transport.
`spec/plugin-abi.md` is updated; the old namespace helper is removed after the
new tests pass.
+122
View File
@@ -0,0 +1,122 @@
# ADR-0011: Capability broker and vendor-namespaced requests
Status: **Accepted**
Date: 2026-11-20
## Context
M0.5 has a useful `Capabilities` struct but no way for an extension to request
a capability at runtime:
* `marqdo-plugin-abi::KNOWN_CAPABILITIES` is a closed list and unknown names are
rejected during manifest validation;
* `Host::load_plugin` passes `LoadOptions::default()`, whose capability handler
is empty, so every plugin `request_capability` is denied;
* adding a new capability requires changing the core enum, the manifest list and
the host dispatch together.
The M0.6 audit (E04/E09/E13) requires a broker: core capabilities stay finite
and auditable, while vendor-namespaced requests are declarative and can execute
only when a trusted host policy provides a handler and the user grants them.
## Decision
### 1. Two capability classes
**Core capabilities** are implemented by the host and keep a fixed list:
`console`, `math.compute`, `fs.read`, `fs.write`, `net.request`, `process`,
`clock`, `random`, `log`, `artifact.record`. They map to concrete host
operations and existing CLI grants.
**Vendor capabilities** match `^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)*$`
and must contain a vendor namespace (for example `vendor.device.read`). A
manifest may declare them, but a declaration is only a request. They never map
to a core operation automatically and cannot spell a core capability with a
different prefix (`fs.read` cannot be recreated as `vendor.fs.read`).
### 2. Broker interface
```rust
pub struct CapabilityRequest<'a> {
pub plugin_instance: &'a str,
pub package: &'a str,
pub capability: &'a str,
pub call_context: &'a ExecutionContext,
pub reason: Option<&'a str>,
}
pub trait CapabilityBroker {
fn authorize(&mut self, request: &CapabilityRequest<'_>) -> Result<CapabilityGrant, RuntimeError>;
fn audit(&mut self, request: &CapabilityRequest<'_>, decision: &CapabilityDecision);
}
```
The CLI installs a broker populated from explicit user grants. The default
broker denies everything not in the effective `Capabilities` set. A vendor
capability is granted only if:
1. a trusted host policy has registered a handler for that exact name;
2. the user explicitly granted it for that package/instance; and
3. the request carries a live `ExecutionContext` (module, span, run id,
generation).
A missing handler is `capability.unavailable`; a missing grant is
`permission.denied`. Both are distinct from runtime errors.
### 3. Budget, audit and scope
Every broker decision records the plugin instance, package, capability, run id
and decision in the effect trace. Grants are scoped to one run and one plugin
instance; they are not reusable across sessions, after unload, or by another
package. Resource limits (fuel, stack, timeout, output) are applied by the host
around the handler, not by the plugin.
### 4. ABI and manifest
The ABI callback signature is unchanged for v1. The loader passes a broker-backed
handler instead of `None`. Unknown **vendor** capability names are accepted by
manifest validation and reported as "requested, requires policy"; unknown core
names are rejected. No vendor capability can bypass `HostOp` dispatch: a
handler must ultimately call a host primitive and is subject to the same budget
and audit checks.
## Alternatives
1. Keep the closed `KNOWN_CAPABILITIES` list and add names as new core
releases. Rejected: every vendor extension would require a core release.
2. Allow arbitrary strings and treat unknown names as granted. Rejected:
privilege escalation by declaration.
3. Let plugins implement their own sockets/processes. Rejected: bypasses the
host and the audit trail.
4. Use the existing `Capabilities` struct only. Rejected: it cannot express
vendor handlers or per-instance/session scope.
## Compatibility
Core capability names and CLI flags remain valid. Manifests that previously
failed with `unknown_capability` for a valid vendor name now validate but still
fail at execution unless a trusted handler and grant exist. ABI v1 layout is
unchanged; future broker fields require an ABI minor/major negotiation.
## Security
The broker is the only path from an extension request to a host primitive. It
checks the actual package instance, not a self-declared name. It records audit
events and cannot mint capabilities from strings. Native in-process plugins are
still trusted code; the broker limits what they can ask the host to do, not what
they can do with their own memory.
## Testing
* authorized plugin reads a project-limited file; unauthorized read/write/
process requests fail with `permission.denied`;
* a vendor capability without a handler fails with `capability.unavailable`;
* a grant cannot be reused by another plugin instance or after unload;
* a manifest cannot declare `fs.*` under a vendor prefix to obtain core access;
* audit entries contain the expected package/capability/decision.
## Migration & rollout
R2 implements the broker and vendor-name validation. `spec/security.md` and
`spec/plugin-abi.md` are updated. Existing plugins that only declare core
capabilities keep the same denied-by-default behavior.
+111
View File
@@ -0,0 +1,111 @@
# ADR-0012: External foreign-kernel providers
Status: **Accepted**
Date: 2026-11-20
## Context
`marqdo-foreign` hard-codes `SUPPORTED_LANGUAGES = ["python", "javascript"]`
and `normalize_language`/`program_candidates` branch on those names. Adding R,
Julia or SQL requires changing the crate and shipping a new interpreter even
though foreign kernels are optional, externally installed programs.
The M0.6 plan (E05, R2) requires a provider registry. A provider is an
**execution kernel** for an inert `Code` value, not a CLI Tool and not a C ABI
plugin.
## Decision
### 1. Descriptor and protocol
```rust
pub struct KernelDescriptor {
pub provider_id: String, // `python`, `javascript`, `mocklang`
pub languages: Vec<String>, // accepted code-fence labels/aliases
pub wire_version: u32, // 1 for the current typed JSON envelope
pub entrypoint: PathBuf, // trusted provider executable/script path
pub digest: Option<String>, // content digest of the provider program
pub permissions_requested: Vec<String>,
}
```
Providers implement the existing `foreign` wire protocol: one request envelope
on stdin, stdout must be exactly one typed wire value for `call`, stderr and a
non-zero exit are errors. A provider receives no secret environment beyond
`PATH` unless explicitly granted.
### 2. Registry
`marqdo_foreign::KernelRegistry` is constructed by the host/CLI:
* built-in providers are registered for `python`/`python3`/`py` and
`javascript`/`js`/`node`/`nodejs` with their existing one-shot command
lines;
* additional providers come from an explicit, versioned `kernel.json`
descriptor (or a future `marqdo.yaml` kernel section);
* registration is static, explicit and user-controlled; no PATH scan for
arbitrary providers and no automatic download.
Lookup happens **only** when `foreign.run`/`foreign.call` is explicitly
invoked. Parsing/rendering a `python`/`r`/unknown fence always yields an inert
`Code` value; an unregistered label is legal until execution, then
`kernel.unavailable`.
### 3. Isolation and authorization
A provider process is a foreign kernel, never the Marqdo interpreter. Spawning
requires `allow_foreign` (or an explicit kernel grant). The host applies
timeout, output cap, process-tree cleanup and environment clearing as today.
A provider descriptor's `permissions_requested` is advisory and cannot grant
filesystem/network access; any such access must be implemented by the provider
inside the same OS-level limits as other foreign processes.
Tool Protocol is deliberately separate: a CLI Tool is a user-invoked native
program; a Kernel Provider executes code requested by an `.mq.md` program. They
do not share registries or trust decisions.
### 4. Versioning
`wire_version` must equal the host's supported version (1) or execution fails
with `kernel.wire_version`. The language labels are case-insensitive and
trimmed; duplicate labels across providers are a registration conflict. The
existing Python/Node detection remains as the built-in provider implementation,
not a special case in the call path.
## Alternatives
1. Keep the hard-coded language list. Rejected by E05.
2. Let a provider be any executable found on PATH by language name. Rejected:
PATH hijacking and implicit execution.
3. Reuse the C ABI plugin manifest. Rejected: different trust model, lifecycle
and wire protocol.
4. Execute unknown languages via a generic shell. Rejected: no explicit
provider, no deterministic protocol, no capability boundary.
## Compatibility
`foreign.run/call` keep their names and wire protocol. Existing Python/Node
programs behave the same. Unknown labels remain inert values; only an explicit
call errors. A future registry source can add providers without changing the
interpreter.
## Security
A provider is untrusted code by default. The host does not treat a descriptor as
a sandbox; it applies the same child-process limits and explicit grant. A
descriptor cannot grant itself core capabilities, and a tool cannot become a
kernel provider implicitly.
## Testing
* register `mocklang` without changing `marqdo-foreign` and execute a typed
call, with timeout/output-limit/denial cases;
* unregistered label yields `kernel.unavailable` only on call;
* duplicate language labels and wire-version mismatch are rejected;
* built-in Python/Node tests continue to pass when the interpreters exist.
## Migration & rollout
R2 introduces the registry and converts Python/Node to built-in descriptors.
R5 may add a declarative kernel section to project/environment sync. No new CLI
top-level command is added; execution still goes through `run/call`.