Author SHA1 Message Date
cflmy c769eafc60 docs: list the Phase A commits in the evidence record
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/pr/main Pipeline was successful
Add the smoke commit and the CI gate follow-up so the evidence names the
reviewed implementation sequence instead of a relative commit.
2026-11-26 15:59:07 +08:00
cflmy 2acaaefe77 ci: fold the independent build into the linux evidence gate
tools/ci/release_evidence.py accepts only its declared gate names; the
extra independent_build gate would have failed the release-evidence job.
The job still depends on independent-build and marks linux FAIL when it
does not pass.
2026-11-26 15:56:20 +08:00
cflmy 88ce91a9e1 docs: record the issue #11 Phase A state and evidence
Update STATUS, the architecture overview, README and tests/README with
the explicit Bundle input, pinned test/perf lanes and the independent
build. Add the Phase A evidence record: bundle identity, failure paths,
deterministic pack/package digests, independent build, archive smoke,
cold install and the 634-passed workspace gate. Phase B remains
explicitly unclaimed.
2026-11-26 15:52:04 +08:00
cflmy 0e1efc713e smoke: keep language-only execution after removing the Bundle
Moving the shipped stdlib aside must fail the print program with an
explicit diagnostic and still run a language-only program. The archive
smoke and the cold-install container now both call the factorial
example after the move, and the archive contract test pins the new
message.
2026-11-26 15:51:39 +08:00
cflmy ab6b6b1a23 ci: add the independent-build lane and pin the perf Bundle
Add tools/ci/independent_build.py: export HEAD without stdlib/, build
both shipped binaries with --locked, run a language-only check/call, and
require a stdlib-dependent run to fail closed with no sibling stdlib.
Add tests/independent/language-only.mq.md and run the lane as its own
GitHub job and Woodpecker step.

Perf runner resolves the pinned Bundle (--stdlib-dir/--bundle-pin),
exports it to every workload and records it in the report; GitHub and
Woodpecker lanes verify the pin and pass the product tests an explicit
Bundle. docs/ci.md and performance docs describe the lanes.
2026-11-26 15:25:40 +08:00
cflmy 3a68260cf2 tests: resolve one pinned Bundle and separate the loader lane
Add crates/cli/tests/support/stdlib.rs as the product/conformance test
resolver: explicit MARQDO_TEST_STDLIB_BUNDLE or the pinned path, always
verified against bundle-pin.json (name/version/commit/digests), with a
bad explicit override failing closed. Route stdlib_product,
stdlib_bundle, http, table, alias routing, p2_closure,
conformance_semantics and architecture_boundaries through it.

Loader unit tests now build small synthetic Bundles; discovery is split
into discover_with so the bad-override-no-fallback rule is testable.
2026-11-26 15:15:59 +08:00
cflmy 422b9de6d7 release: take the stdlib Bundle as one explicit, pinned input
package.py now requires --stdlib-dir and accepts --bundle-pin; it
verifies the manifest, required files, tree/alias digests and the pin
before staging, copies exactly that Bundle next to the binary, and
records stdlib.source{kind,repository,commit,path} in RELEASE_INFO.
Digest logic moves to tools/stdlib/bundle.py. GitHub/Woodpecker
release steps and docs/releasing.md pass the pinned input.
2026-11-26 15:07:29 +08:00
cflmy 1b9d9c4c26 stdlib: add one pinned Bundle resolver and explicit pack input
Add tools/stdlib/bundle.py + bundle-pin.json as the single source-side
Bundle identity (name, version, source commit, tree/alias digests) and
require tools/pack-stdlib.py --stdlib-dir instead of reading the
checkout implicitly. Missing input, missing manifest, digest/alias
mismatch, pin mismatch and symlinks fail closed; two packs are
byte-identical. Tests: tools/ci/test_stdlib_bundle_tools.py.
2026-11-26 15:00:26 +08:00
cflmy b9c72e1d2a docs: inventory stdlib source coupling and record the Phase A boundary
Record ADR-0070 (one explicit stdlib Bundle build input) and the
issue #11 Phase A inventory of every direct checkout-stdlib reference.
Baseline 4bbefc9; bundle source 2cbde54; no runtime contract change.
2026-11-26 14:54:11 +08:00
cflmy 4bbefc9244 release: publish 3.0.0-rc.4 with analysis boundary evidence
ci/woodpecker/push/main Pipeline was successful
Record the RC_RELEASE_CANDIDATE gate manifest, same-SHA CI #94, frozen
extension 7/7, archive smoke, Ubuntu 24.04 cold install, disposable-VM strict
L1 PASS (uid 1000), archived-binary VM verification and the maintainer-approved
shared-node performance WARN for this named RC. Document that stable/LTS still
requires a dedicated fixed node and link the downstream view/lint issues.
2026-11-25 14:17:31 +08:00
cflmy 452e9a32bd docs: define RC shared-node policy and downstream Analysis integration
ci/woodpecker/push/main Pipeline was successful
RC candidates may use a maintainer-approved shared node with a recorded WARN;
stable/LTS still requires a dedicated fixed node. Add the migration guide for
marqdo-view and marqdo-lint covering exact source/AST consumption, the changed
unit span meaning, the stateful reference contract and the rejection of old
same-revision artifacts.
2026-11-25 13:19:41 +08:00
cflmy 63f62d5728 Merge issue #10: close the public Analysis boundary
ci/woodpecker/push/main Pipeline was successful
Replace the program-only Analysis v3 shape in place with the ADR-0069 boundary:
exact source and document AST, complete heading scope, entry/snapshot identity,
one shared document-link resolver, typed call/reference facts, semantic
validation and owner-only atomic emit. All code/CI/archive/conformance gates pass;
rc.4 publication is withheld (DO_NOT_RELEASE) pending the strict-VM and approved
G4 gates.
2026-11-25 11:55:36 +08:00
52 changed files with 2732 additions and 389 deletions

No files matched your search

+21 -4
View File
@@ -19,6 +19,8 @@ jobs:
components: rustfmt, clippy
- name: Rust cache
uses: Swatinem/rust-cache@v2
- name: Verify the pinned stdlib Bundle
run: python3 tools/stdlib/bundle.py
- name: Formatting
run: cargo fmt --all -- --check
- name: Clippy
@@ -41,7 +43,10 @@ jobs:
run: cargo test -p marqdo-cli --test architecture_boundaries
- name: CI evidence tool tests
run: python3 -m unittest discover -s tools/ci -p "test_*.py"
- name: Whole stdlib product tests
- name: Whole stdlib product tests (explicit pinned Bundle)
env:
MARQDO_TEST_STDLIB_BUNDLE: ${{ github.workspace }}/stdlib
MARQDO_TEST_BUNDLE_PIN: ${{ github.workspace }}/tools/stdlib/bundle-pin.json
run: cargo test -p marqdo-cli --test stdlib_product
- name: Validate public JSON schemas
run: |
@@ -93,6 +98,16 @@ jobs:
--trust-native-plugin \
--allow-plugin demo.solver
independent-build:
name: independent CLI/worker build (no stdlib source)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build from a copy without stdlib and run a language-only program
run: python3 tools/ci/independent_build.py
schema:
name: schema instance validation + consumers
runs-on: ubuntu-latest
@@ -221,7 +236,8 @@ jobs:
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
version="$(cargo metadata --no-deps --format-version 1 --offline \
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version"
python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version" \
--stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$GITHUB_SHA" dist/frozen-extension-evidence.json
- uses: actions/upload-artifact@v4
@@ -239,7 +255,7 @@ jobs:
release-evidence:
name: release evidence manifest
needs: [test, schema, cross-platform, frozen-extensions]
needs: [test, schema, cross-platform, frozen-extensions, independent-build]
if: always()
runs-on: ubuntu-latest
steps:
@@ -252,6 +268,7 @@ jobs:
LINUX_RESULT: ${{ needs.test.result }}
SCHEMA_RESULT: ${{ needs.schema.result }}
EXTENSIONS_RESULT: ${{ needs.frozen-extensions.result }}
INDEPENDENT_RESULT: ${{ needs.independent-build.result }}
run: |
set -euo pipefail
state() {
@@ -262,7 +279,7 @@ jobs:
esac
}
linux="$(state "$LINUX_RESULT")"
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ]; then
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ] || [ "$(state "$INDEPENDENT_RESULT")" != "PASS" ]; then
linux="FAIL"
fi
python3 tools/ci/release_evidence.py --profile rc --target-sha "$TARGET_SHA" \
+12 -2
View File
@@ -39,6 +39,7 @@ steps:
- apt-get install -y --no-install-recommends curl ca-certificates python3 python3-jsonschema build-essential gcc-mingw-w64-x86-64
- curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
- apt-get install -y --no-install-recommends nodejs
- python3 tools/stdlib/bundle.py
- cargo fmt --all -- --check
- cargo clippy --workspace --all-targets -- -D warnings
# Provider CLI tests resolve a real provider worker next to the CLI
@@ -48,12 +49,19 @@ steps:
- cargo test -p marqdo-cli --test docs_consistency
- cargo test -p marqdo-cli --test architecture_boundaries
- python3 -m unittest discover -s tools/ci -p "test_*.py"
- cargo test -p marqdo-cli --test stdlib_product
- MARQDO_TEST_STDLIB_BUNDLE="$PWD/stdlib" MARQDO_TEST_BUNDLE_PIN="$PWD/tools/stdlib/bundle-pin.json" cargo test -p marqdo-cli --test stdlib_product
# Windows compile gate: runtime lanes are native on GitHub; this catches
# cfg/compile regressions on the Linux CI without a Windows runner.
- rustup target add x86_64-pc-windows-gnu
- cargo check --workspace --all-targets --target x86_64-pc-windows-gnu
independent-build:
image: rust:1.100-bookworm
commands:
- apt-get update
- apt-get install -y --no-install-recommends ca-certificates git python3
- python3 tools/ci/independent_build.py
minimum-rust:
image: rust:1.89-bookworm
commands:
@@ -71,13 +79,15 @@ steps:
# only supported transport and resolution is a sibling-of-CLI lookup.
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- test -x target/release/marqdo-provider-worker
- python3 tools/stdlib/bundle.py
# Build the deterministic archive from this exact commit and cold-install
# smoke-test it; the package script refuses a dirty tree or wrong SHA.
- |
set -eu
version="$(cargo metadata --no-deps --format-version 1 --offline \
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version"
python3 tools/release/package.py --source-sha "$CI_COMMIT_SHA" --version "$version" \
--stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$CI_COMMIT_SHA" dist/frozen-extension-evidence.json
cat dist/frozen-extension-evidence.json
+5 -2
View File
@@ -10,6 +10,7 @@ steps:
commands:
- apt-get update
- apt-get install -y --no-install-recommends python3 util-linux ca-certificates git openssl build-essential
- python3 tools/stdlib/bundle.py
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- |
set -eu
@@ -22,7 +23,8 @@ steps:
(cd "$perf_dir/beta" && cargo build --release --locked -p marqdo-cli)
version="$(target/release/marqdo --version | cut -d ' ' -f 2)"
python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" --out-dir "$perf_dir"
python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" \
--stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json --out-dir "$perf_dir"
archive="$perf_dir/marqdo-$version-x86_64-unknown-linux-gnu.tar.gz"
(cd "$perf_dir" && sha256sum -c "$(basename "$archive.sha256")")
tar -xzf "$archive" -C "$perf_dir"
@@ -37,7 +39,8 @@ steps:
(cd "$perf_dir/beta" && python3 tools/perf/runner.py --no-build \
--warmups 5 --samples 20 --platform-id woodpecker-agent-1 \
--cpu-list "$cpu_list" --out "$perf_dir/beta.json" > /dev/null)
python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" --warmups 5 --samples 20 \
python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" \
--stdlib-dir "$candidate/stdlib" --warmups 5 --samples 20 \
--platform-id woodpecker-agent-1 --cpu-list "$cpu_list" \
--baseline "$perf_dir/beta.json" --out perf.json > /dev/null
python3 - <<'PY'
+3 -2
View File
@@ -14,11 +14,12 @@ separately and do not follow the product version. Dates use ISO 8601.
Older sections are release records: a retired option or spec they name is
available at its tagged commit, not in the current tree.
## 3.0.0-rc.4 (2026-11-25, candidate)
## 3.0.0-rc.4 (2026-11-25)
- The Rust workspace, CLI version output and protocol producers report
`3.0.0-rc.4`; the supported platform remains Linux x86_64 on glibc 2.39 and
the locked Rust minimum remains 1.89.
the locked Rust minimum remains 1.89. Released as tag `v3.0.0-rc.4` at
`452e9a32bd9e40dba427d4180691c58bab74449e`.
### Closed public Analysis boundary — issue #10 (breaking in place)
+6 -3
View File
@@ -1,7 +1,10 @@
# Compatibility and support matrix
Snapshot: product version **`3.0.0-rc.4`** (prerelease candidate, 2026-11-25).
The previous release is `3.0.0-rc.3` at source SHA
Snapshot: product version **`3.0.0-rc.4`** (prerelease, released 2026-11-25).
Tag `v3.0.0-rc.4` at source SHA
`452e9a32bd9e40dba427d4180691c58bab74449e`; release
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4. The previous
release is `3.0.0-rc.3` at source SHA
`1e2a045cc78bf40972181abb44e7117c56cf4401`; its evidence remains under
[`docs/evidence/`](docs/evidence/2026-11-24-rc.3-release.md). This file records
what was actually verified and separates it from what is only implemented. The
@@ -10,7 +13,7 @@ experimental and not claimed for this prerelease. Executed status and SHA-bound
evidence are in [`docs/STATUS.md`](docs/STATUS.md) and
[`docs/evidence/`](docs/evidence/).
The `3.0.0-rc.4` candidate includes the post-beta protocol convergence and the
The `3.0.0-rc.4` release includes the post-beta protocol convergence and the
closed public Analysis boundary below. See the
[RC acceptance procedure](docs/releasing.md). The platform evidence table
records the beta, rc.1/rc.2/rc.3 and rc.4 candidate verification.
+19 -1
View File
@@ -27,7 +27,10 @@ release policy.
> [`docs/STATUS.md`](docs/STATUS.md) and
> [`docs/migration/README.md`](docs/migration/README.md).
> **Published baseline: `3.0.0-beta.1` prerelease** —
> **Current release: `3.0.0-rc.4` prerelease** —
> [release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4),
> source `452e9a32bd9e40dba427d4180691c58bab74449e`, Linux x86_64. The previous
> published baseline was `3.0.0-beta.1` —
> [release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1),
> source `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. The public beta target is **Linux x86_64 (glibc)**; macOS and Windows are experimental and not claimed, and the
> C ABI plugin/provider paths are Linux-only in this beta. The language
@@ -60,6 +63,21 @@ cargo build -p marqdo-cli
# binary: target/debug/marqdo (or $CARGO_TARGET_DIR/debug/marqdo)
```
The CLI and Provider Worker compile without the stdlib sources. A release is
assembled from one explicit, verified Bundle (ADR-0070); the debug CLI still
discovers the checkout's `stdlib/` for the development loop, and
`MARQDO_STDLIB_DIR` is the explicit runtime override:
```bash
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
python3 tools/stdlib/bundle.py --print-path
python3 tools/release/package.py --source-sha "$(git rev-parse HEAD)" \
--version <version> --stdlib-dir stdlib \
--bundle-pin tools/stdlib/bundle-pin.json
```
See [`docs/releasing.md`](docs/releasing.md) for the full procedure.
## Quickstart
```bash
+61 -44
View File
@@ -51,14 +51,24 @@ impl StdlibBundle {
/// machine path: the release archive must ship a verified `stdlib/` next to
/// the binary (RFC-EXT-0003 H-08, ADR).
pub fn discover() -> Result<Option<Self>, String> {
if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) {
return Self::load(PathBuf::from(dir)).map(Some);
let override_dir = std::env::var_os(STDLIB_DIR_ENV).map(PathBuf::from);
let exe_dir = std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(Path::to_path_buf));
Self::discover_with(override_dir, exe_dir)
}
/// Discovery with the explicit override and the executable directory passed
/// in. The override is authoritative: a bad `MARQDO_STDLIB_DIR` fails even
/// when a valid sibling Bundle exists (no silent fallback).
fn discover_with(
override_dir: Option<PathBuf>,
exe_dir: Option<PathBuf>,
) -> Result<Option<Self>, String> {
if let Some(dir) = override_dir {
return Self::load(dir).map(Some);
}
Self::discover_from_exe_dir(
std::env::current_exe()
.ok()
.and_then(|exe| exe.parent().map(Path::to_path_buf)),
)
Self::discover_from_exe_dir(exe_dir)
}
/// Discover from the directory that holds the executable, without the explicit
@@ -454,21 +464,41 @@ pub fn aliases_digest(aliases: &[PublicAlias]) -> String {
mod tests {
use super::*;
fn dev_bundle() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("..")
.join("..")
.join("stdlib")
/// A small synthetic Bundle so loader unit tests never depend on the
/// product tree (ADR-0070 test-lane separation).
fn write_synthetic_bundle(root: &Path) {
for (relative, body) in [
("io.mq.md", "## @knowledge test\n"),
("io/console.mq.md", "## @knowledge console\n"),
] {
let path = root.join(relative);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, body).unwrap();
}
let digest = tree_digest(root).unwrap();
let manifest = serde_json::json!({
"name": "test-stdlib",
"version": "0.0.0-test",
"digest": digest,
});
std::fs::write(
root.join("stdlib.json"),
serde_json::to_vec(&manifest).unwrap(),
)
.unwrap();
}
#[test]
fn dev_bundle_verifies_and_resolves() {
let bundle = StdlibBundle::load(dev_bundle()).unwrap();
assert!(bundle.digest.starts_with("sha256:"));
fn synthetic_bundle_verifies_and_resolves() {
let dir = tempfile::tempdir().unwrap();
write_synthetic_bundle(dir.path());
let bundle = StdlibBundle::load(dir.path()).unwrap();
assert_eq!(bundle.version(), "0.0.0-test");
let io = bundle.resolve("io").unwrap();
assert_eq!(io.relative_path, "io.mq.md");
assert!(io.package.instance_id.starts_with("std:marqdo-stdlib@"));
assert!(io.package.instance_id.starts_with("std:test-stdlib@"));
assert!(bundle.resolve("../escape").is_err());
assert!(bundle.resolve("/absolute").is_err());
}
#[test]
@@ -476,44 +506,31 @@ mod tests {
let dir = tempfile::tempdir().unwrap();
let bundle = dir.path().join("stdlib");
std::fs::create_dir_all(&bundle).unwrap();
for entry in std::fs::read_dir(dev_bundle()).unwrap() {
let entry = entry.unwrap();
let target = bundle.join(entry.file_name());
if entry.path().is_dir() {
copy_dir(&entry.path(), &target);
} else {
std::fs::copy(entry.path(), target).unwrap();
}
}
write_synthetic_bundle(&bundle);
let found = StdlibBundle::discover_from_exe_dir(Some(dir.path().to_path_buf()))
.unwrap()
.expect("sibling stdlib");
assert_eq!(found.root, bundle.canonicalize().unwrap());
assert_eq!(found.root(), bundle.canonicalize().unwrap());
}
fn copy_dir(source: &std::path::Path, target: &std::path::Path) {
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(source).unwrap() {
let entry = entry.unwrap();
let destination = target.join(entry.file_name());
if entry.path().is_dir() {
copy_dir(&entry.path(), &destination);
} else {
std::fs::copy(entry.path(), destination).unwrap();
}
}
#[test]
fn bad_override_fails_closed_even_with_a_valid_sibling() {
let dir = tempfile::tempdir().unwrap();
let sibling = dir.path().join("stdlib");
std::fs::create_dir_all(&sibling).unwrap();
write_synthetic_bundle(&sibling);
let error = StdlibBundle::discover_with(
Some(dir.path().join("missing")),
Some(dir.path().to_path_buf()),
)
.unwrap_err();
assert!(error.contains("cannot open stdlib directory"), "{error}");
}
#[test]
fn digest_tamper_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let source = dev_bundle();
for entry in std::fs::read_dir(&source).unwrap() {
let entry = entry.unwrap();
if entry.path().is_file() {
std::fs::copy(entry.path(), dir.path().join(entry.file_name())).unwrap();
}
}
write_synthetic_bundle(dir.path());
std::fs::write(dir.path().join("io.mq.md"), "## @knowledge tampered\n").unwrap();
let error = StdlibBundle::load(dir.path()).unwrap_err();
assert!(error.contains("digest mismatch"), "{error}");
+13 -3
View File
@@ -6,6 +6,9 @@
//! stdio/file/TCP resource endpoints. They are source and digest checks, not an
//! OS-sandbox proof.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use sha2::{Digest, Sha256};
@@ -88,7 +91,14 @@ fn runtime_depends_on_the_host_platform_layer_without_a_cycle() {
#[test]
fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() {
let root = repo_root().join("stdlib");
let root = stdlib_support::bundle_dir();
// Phase A (ADR-0070): the pinned Bundle is still the checkout tree. Phase B
// replaces this assertion when the ecosystem Bundle becomes the input.
assert_eq!(
root,
repo_root().join("stdlib").canonicalize().unwrap(),
"the Phase A stdlib pin must resolve to the in-repo stdlib tree"
);
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
assert_eq!(manifest["name"], "marqdo-stdlib");
@@ -103,7 +113,7 @@ fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() {
#[test]
fn stdlib_imports_resolve_inside_the_bundle() {
let root = repo_root().join("stdlib");
let root = stdlib_support::bundle_dir();
for entry in walk_markdown(&root) {
let is_test = entry.starts_with(root.join("tests"));
let text = read(&entry);
@@ -439,7 +449,7 @@ const _: fn(marqdo_value::Value) = |value| match value {
/// hard-coded runtime names. Recompute the canonical metadata digest.
#[test]
fn official_stdlib_public_aliases_are_verified_metadata() {
let root = repo_root().join("stdlib");
let root = stdlib_support::bundle_dir();
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
let aliases = manifest["public_aliases"]
+5 -2
View File
@@ -20,6 +20,9 @@
//! expectation; the checked-in goldens were reviewed individually.
use std::fs;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use marqdo_host::{Capabilities, Host, StdHost};
@@ -291,7 +294,7 @@ fn normalise_relative(path: &Path) -> String {
/// unique registry, run the single binding pass and install its table. There is
/// no `print_override` and no runtime name guessing.
fn bind_calls_with_stdlib_aliases(program: &mut Program) {
let root = repo_root().join("stdlib");
let root = stdlib_support::bundle_dir();
let mut loaded = std::collections::BTreeSet::new();
let mut official = Vec::new();
if root.join("stdlib.json").is_file() {
@@ -428,7 +431,7 @@ fn install_entry_stdlib_imports(
module_id: &ModuleId,
analysis: &marqdo_frontend::AnalysisResult,
) {
let root = repo_root().join("stdlib");
let root = stdlib_support::bundle_dir();
let Some(imports) = analysis
.document
.frontmatter()
+7 -3
View File
@@ -3,6 +3,9 @@
#[path = "support/observation.rs"]
pub mod observation;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::Command;
@@ -109,7 +112,8 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
#[test]
fn p2_stdlib_table_also_runs_in_pure_mode() {
let path = repo_root().join("stdlib").join("tests").join("table.mq.md");
let bundle = stdlib_support::bundle_dir();
let path = bundle.join("tests").join("table.mq.md");
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args([
"run",
@@ -119,8 +123,8 @@ fn p2_stdlib_table_also_runs_in_pure_mode() {
"--output",
"json",
])
.current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.current_dir(&bundle)
.env("MARQDO_STDLIB_DIR", &bundle)
.output()
.expect("run table self-test");
assert_eq!(
+4 -10
View File
@@ -5,6 +5,9 @@
//! runtime name special case and no hard-coded per-function scan.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
@@ -35,15 +38,6 @@ impl Drop for TempDir {
}
}
fn repo() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn cli(args: &[&str], dir: &Path, env: &[(&str, &Path)]) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo"));
command.args(args).current_dir(dir);
@@ -62,7 +56,7 @@ fn stdout(output: &Output) -> String {
}
fn copy_stdlib(target: &Path) {
let source = repo().join("stdlib");
let source = stdlib_support::bundle_dir();
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(&source).unwrap() {
let entry = entry.unwrap();
+4 -10
View File
@@ -1,23 +1,17 @@
//! Bundled stdlib (`std:`) and frozen-CLI closure tests (CM-A10).
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::Command;
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn stdlib_dir() -> PathBuf {
repo_root().join("stdlib")
stdlib_support::bundle_dir()
}
fn run(dir: &Path, stdlib: &Path, args: &[&str]) -> std::process::Output {
+6 -12
View File
@@ -3,24 +3,18 @@
#[path = "support/observation.rs"]
pub mod observation;
use std::path::Path;
use std::process::Command;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
fn repo_root() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
use std::process::Command;
#[test]
fn stdlib_http_parses_chunked_responses_and_builds_requests() {
let bundle = stdlib_support::bundle_dir();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/http.mq.md", "--output", "json"])
.current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.current_dir(&bundle)
.env("MARQDO_STDLIB_DIR", &bundle)
.output()
.expect("run http self-test");
assert_eq!(
+5 -11
View File
@@ -8,20 +8,14 @@
#[path = "support/observation.rs"]
pub mod observation;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::{Mutex, MutexGuard};
fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
static FS_LOCK: Mutex<()> = Mutex::new(());
fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> {
@@ -33,7 +27,7 @@ fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> {
}
fn stdlib_dir() -> PathBuf {
repo_root().join("stdlib")
stdlib_support::bundle_dir()
}
struct TestFile {
+6 -12
View File
@@ -3,23 +3,17 @@
#[path = "support/observation.rs"]
pub mod observation;
use std::path::Path;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::process::Command;
fn repo_root() -> std::path::PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn run_table_self_test() -> serde_json::Value {
let bundle = stdlib_support::bundle_dir();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run", "tests/table.mq.md", "--output", "json"])
.current_dir(repo_root().join("stdlib"))
.env("MARQDO_STDLIB_DIR", repo_root().join("stdlib"))
.current_dir(&bundle)
.env("MARQDO_STDLIB_DIR", &bundle)
.output()
.expect("run table self-test");
assert_eq!(
+356
View File
@@ -0,0 +1,356 @@
//! Pinned stdlib Bundle resolver shared by test harnesses (ADR-0070).
//!
//! Product tests consume one explicit Bundle whose identity is pinned in
//! `tools/stdlib/bundle-pin.json` (name, version, source commit, tree digest and
//! alias digest). `MARQDO_TEST_STDLIB_BUNDLE` may change the location, but the
//! Bundle must still match the pin; `MARQDO_TEST_BUNDLE_PIN` may change the pin
//! file. A bad explicit input fails even when the default location is valid —
//! there is no silent fallback.
use std::path::{Component, Path, PathBuf};
use sha2::{Digest, Sha256};
pub const BUNDLE_ENV: &str = "MARQDO_TEST_STDLIB_BUNDLE";
pub const PIN_ENV: &str = "MARQDO_TEST_BUNDLE_PIN";
/// The checkout root (this test support module lives in `crates/cli/tests`).
pub fn repo_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("crates directory")
.parent()
.expect("repository root")
.to_path_buf()
}
/// Pin file path, overridable for a candidate Bundle.
pub fn pin_path() -> PathBuf {
std::env::var_os(PIN_ENV)
.map(PathBuf::from)
.unwrap_or_else(|| {
repo_root()
.join("tools")
.join("stdlib")
.join("bundle-pin.json")
})
}
/// One pinned Bundle identity (`tools/stdlib/bundle-pin.json`).
#[derive(Debug, Clone)]
pub struct BundlePin {
pub name: String,
pub version: String,
pub source_commit: String,
pub source_path: PathBuf,
pub tree_digest: String,
pub aliases_digest: String,
}
impl BundlePin {
pub fn load(path: &Path) -> Self {
let text = std::fs::read_to_string(path)
.unwrap_or_else(|error| panic!("cannot read Bundle pin {}: {error}", path.display()));
let value: serde_json::Value = serde_json::from_str(&text)
.unwrap_or_else(|error| panic!("invalid Bundle pin {}: {error}", path.display()));
assert_eq!(
value.get("schema").and_then(serde_json::Value::as_str),
Some("marqdo.stdlib-bundle-pin"),
"{} must use the marqdo.stdlib-bundle-pin schema",
path.display()
);
assert_eq!(
value
.get("schema_version")
.and_then(serde_json::Value::as_u64),
Some(1),
"{} must use pin schema_version 1",
path.display()
);
let source = value
.get("source")
.unwrap_or_else(|| panic!("Bundle pin {} has no source object", path.display()));
let source_path = source
.get("path")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| panic!("Bundle pin {} has no source.path", path.display()));
validate_relative(source_path)
.unwrap_or_else(|error| panic!("Bundle pin {} source.path: {error}", path.display()));
Self {
name: required_str(&value, "name", path),
version: required_str(&value, "version", path),
source_commit: required_str(source, "commit", path),
source_path: PathBuf::from(source_path),
tree_digest: required_str(&value, "tree_digest", path),
aliases_digest: required_str(&value, "aliases_digest", path),
}
}
/// The committed pin for the current checkout.
pub fn committed() -> Self {
Self::load(&pin_path())
}
}
fn required_str(value: &serde_json::Value, field: &str, path: &Path) -> String {
value
.get(field)
.and_then(serde_json::Value::as_str)
.filter(|text| !text.is_empty())
.unwrap_or_else(|| panic!("Bundle pin {} has no `{field}`", path.display()))
.to_string()
}
/// One verified Bundle on disk.
#[derive(Debug, Clone)]
pub struct Bundle {
root: PathBuf,
pub name: String,
pub version: String,
pub tree_digest: String,
pub aliases_digest: String,
}
impl Bundle {
/// Resolve the Bundle for a product test: explicit override or pinned path,
/// verified against the pin.
pub fn pinned() -> Self {
let pin = BundlePin::committed();
let explicit = std::env::var_os(BUNDLE_ENV).map(PathBuf::from);
let root = explicit
.clone()
.unwrap_or_else(|| repo_root().join(&pin.source_path));
let bundle = Self::verify(&root).unwrap_or_else(|error| match &explicit {
Some(_) => panic!(
"{BUNDLE_ENV} does not name a valid stdlib Bundle at {}: {error}",
root.display()
),
None => panic!(
"pinned stdlib Bundle at {} is invalid: {error}",
root.display()
),
});
let mismatches = [
("name", &pin.name, &bundle.name),
("version", &pin.version, &bundle.version),
("tree_digest", &pin.tree_digest, &bundle.tree_digest),
(
"aliases_digest",
&pin.aliases_digest,
&bundle.aliases_digest,
),
];
for (field, expected, actual) in mismatches {
assert_eq!(
expected,
actual,
"stdlib Bundle at {} does not match the pin field `{field}`",
root.display()
);
}
for required in ["stdlib.json", "io.mq.md", "io/console.mq.md"] {
assert!(
bundle.root.join(required).is_file(),
"stdlib Bundle at {} is missing required file {required}",
bundle.root.display()
);
}
assert_eq!(
pin.source_commit.len(),
40,
"the pin must record a full source commit, got {:?}",
pin.source_commit
);
bundle
}
/// Verify one unpacked Bundle root.
pub fn verify(root: &Path) -> Result<Self, String> {
if !root.is_dir() {
return Err(format!("not a directory: {}", root.display()));
}
let manifest_path = root.join("stdlib.json");
if !manifest_path.is_file() {
return Err(format!("missing manifest: {}", manifest_path.display()));
}
let text = std::fs::read_to_string(&manifest_path)
.map_err(|error| format!("cannot read {}: {error}", manifest_path.display()))?;
let manifest: serde_json::Value = serde_json::from_str(&text)
.map_err(|error| format!("invalid {}: {error}", manifest_path.display()))?;
let name = manifest
.get("name")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("{} has no name", manifest_path.display()))?
.to_string();
let version = manifest
.get("version")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("{} has no version", manifest_path.display()))?
.to_string();
let declared = manifest
.get("digest")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| format!("{} has no digest", manifest_path.display()))?
.to_string();
let actual = tree_digest(root)?;
if declared != actual {
return Err(format!(
"tree digest mismatch: stdlib.json declares {declared}, the files are {actual}"
));
}
let aliases = manifest
.get("public_aliases")
.and_then(serde_json::Value::as_array)
.cloned()
.unwrap_or_default();
let declared_aliases = manifest
.get("aliases_digest")
.and_then(serde_json::Value::as_str)
.map(ToString::to_string);
let actual_aliases = aliases_digest(&aliases);
match (declared_aliases, aliases.is_empty()) {
(Some(declared_aliases), _) => {
if declared_aliases != actual_aliases {
return Err(format!(
"alias digest mismatch: stdlib.json declares {declared_aliases}, \
the alias table is {actual_aliases}"
));
}
}
(None, false) => {
return Err(format!(
"{} declares public_aliases without aliases_digest",
manifest_path.display()
));
}
(None, true) => {}
}
Ok(Self {
root: root
.canonicalize()
.map_err(|error| format!("cannot canonicalize {}: {error}", root.display()))?,
name,
version,
tree_digest: actual,
aliases_digest: actual_aliases,
})
}
pub fn root(&self) -> &Path {
&self.root
}
}
/// Resolve and verify the pinned Bundle once per test process.
pub fn bundle() -> &'static Bundle {
static BUNDLE: std::sync::OnceLock<Bundle> = std::sync::OnceLock::new();
BUNDLE.get_or_init(Bundle::pinned)
}
/// Bundle root for fixtures and `MARQDO_STDLIB_DIR`.
pub fn bundle_dir() -> PathBuf {
bundle().root().to_path_buf()
}
/// Content digest over all `.mq.md` files: sorted relative path, NUL, bytes, NUL.
pub fn tree_digest(root: &Path) -> Result<String, String> {
let mut files = Vec::new();
collect_markdown(root, root, &mut files)?;
files.sort();
let mut hasher = Sha256::new();
for (relative, path) in files {
let bytes = std::fs::read(&path)
.map_err(|error| format!("cannot read {}: {error}", path.display()))?;
hasher.update(relative.as_bytes());
hasher.update([0]);
hasher.update(&bytes);
hasher.update([0]);
}
Ok(format!("sha256:{}", hex(&hasher.finalize())))
}
/// Canonical digest over the official public-alias table.
pub fn aliases_digest(aliases: &[serde_json::Value]) -> String {
let mut entries: Vec<&serde_json::Value> = aliases.iter().collect();
entries.sort_by_key(|alias| {
(
alias["target_module"].as_str().unwrap_or("").to_string(),
alias["target_function"].as_str().unwrap_or("").to_string(),
)
});
let mut hasher = Sha256::new();
for alias in entries {
if let Some(module) = alias["target_module"].as_str() {
hasher.update(module.as_bytes());
}
hasher.update([0]);
if let Some(function) = alias["target_function"].as_str() {
hasher.update(function.as_bytes());
}
hasher.update([0]);
let mut names: Vec<&str> = alias["public_names"]
.as_array()
.map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
.unwrap_or_default();
names.sort();
for name in names {
hasher.update(name.as_bytes());
hasher.update([0]);
}
}
format!("sha256:{}", hex(&hasher.finalize()))
}
fn collect_markdown(
root: &Path,
dir: &Path,
out: &mut Vec<(String, PathBuf)>,
) -> Result<(), String> {
let entries = std::fs::read_dir(dir)
.map_err(|error| format!("cannot read {}: {error}", dir.display()))?;
for entry in entries {
let entry = entry.map_err(|error| format!("cannot read {}: {error}", dir.display()))?;
let path = entry.path();
if path.is_dir() {
collect_markdown(root, &path, out)?;
} else if path
.file_name()
.is_some_and(|name| name.to_string_lossy().ends_with(".mq.md"))
{
let relative = path
.strip_prefix(root)
.map_err(|_| "stdlib file escaped its root".to_string())?
.components()
.map(|component| component.as_os_str().to_string_lossy().to_string())
.collect::<Vec<_>>()
.join("/");
out.push((relative, path));
}
}
Ok(())
}
fn validate_relative(path: &str) -> Result<(), String> {
let mut normalised = PathBuf::new();
for component in Path::new(path).components() {
match component {
Component::Normal(part) => normalised.push(part),
Component::CurDir => {}
Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
return Err("must be a relative path inside the repository".to_string())
}
}
}
if normalised.as_os_str().is_empty() {
return Err("must not be empty".to_string());
}
Ok(())
}
fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes {
out.push_str(&format!("{byte:02x}"));
}
out
}
+1 -1
View File
@@ -38,7 +38,7 @@
3. 冻结 CLI 的外部仓库黑盒验收在**发布 SHA**重新执行,至少 pure pinned-Git 包、Callable Worker、陌生 Foreign Kernel、Provider v2、Tool/Analysis/Trace、权限负例及工件改动负例全部 PASS;生成并校验 `docs/evidence/extension/<SHA>/manifest.json`。
4. 冷安装、离线 `--version`/`--help`、`check/run/call`、lock/sync、Tool 安装与分发、Provider Worker 启动、错 SHA/错目标/未授权拒绝全部由发布归档中的**实际二进制**完成;不得依赖开发源码目录。
5. **不得虚假宣传安全隔离。** 发布包若保留并开放 Linux `strict`,必须有该 SHA 的真实 G3 隔离负例证据;若暂无证据,需采用明确经过测试的 fail-closed 禁用方式并在公告中写 `strict: unsupported`。不允许仅改 README 却继续将未验证的 `strict` 描述为安全保障。Beta 的这一策略必须经维护者明确签字并由 CI 可复查。
6. G4 基准不得造假;若当期固定节点仍是 WARN,可由维护者批准 **Beta-only WARN** 并公开环境和限制;必须通过 9 个正确性基准,不允许数值漂移或已确认的灾难性回退。
6. G4 基准不得造假;若当期固定节点仍是 WARN,可由维护者批准 **Beta/RC-only WARN** 并公开环境和限制;必须通过正确性基准,不允许数值漂移或已确认的灾难性回退。RC 允许经维护者批准的共享节点 WARN;最终 stable/LTS 必须使用专用固定节点,该共享节点例外不延续到 LTS。
7. 明确产品版本 `3.0.0-beta.1` 与协议独立版本;工具 SemVer 协商在真实测试版上可安装、拒绝不兼容范围、不会误把 `<1` 当成支持 3.x。
8. `README`、`CHANGELOG`、`COMPATIBILITY`、`docs/STATUS`、`docs/releasing`、协议入口页、迁移说明,均更新至同一事实基线;无“未实现却声称已发布”或“已实现仍称 Proposed”的矛盾。
9. 不发布未经实际构建/烟测的平台二进制;产物附 SHA256、SOURCE_SHA、构建工具链信息和已知限制。
+77 -27
View File
@@ -1,7 +1,9 @@
# Marqdo Implementation Status
Snapshot: **2026-11-25**, product version **`3.0.0-rc.4`** (prerelease
candidate). The previous release is `3.0.0-rc.3` at source SHA
Snapshot: **2026-11-25**, product version **`3.0.0-rc.4`** (prerelease,
released). Tag `v3.0.0-rc.4` at source SHA
**`452e9a32bd9e40dba427d4180691c58bab74449e`**; release:
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4. The previous release is `3.0.0-rc.3` at source SHA
**`1e2a045cc78bf40972181abb44e7117c56cf4401`**; release:
https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.3. The supported
platform is **Linux x86_64 (glibc 2.39)**. The rc.3 same-SHA gate aggregate is
@@ -19,9 +21,11 @@ Authoritative release policy:
evidence). Support matrix: [`../COMPATIBILITY.md`](../COMPATIBILITY.md).
Developer entry point: [`developers/README.md`](developers/README.md).
This file records what was actually executed. "Implemented" does not mean
"verified on every platform"; the evidence column says which commands were run
and where. Status is generated from executed commands/logs; a gate row without a
The rc.4 same-SHA gate aggregate is
[`evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json`](evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json)
(decision `RC_RELEASE_CANDIDATE`). This file records what was actually executed.
"Implemented" does not mean "verified on every platform"; the evidence column
says which commands were run and where. Status is generated from executed commands/logs; a gate row without a
command, log or source path is a defect, not a state. Historical snapshots
(including M0.5 and the pre-beta `0.1.0` candidate) are preserved under
[`history/`](history/README.md) and [`evidence/`](evidence/) and must not be read
@@ -30,12 +34,10 @@ as current status.
## RC candidate
The workspace reports `3.0.0-rc.4` and declares Rust 1.89 as its locked
minimum. Linux x86_64 on glibc 2.39 is the candidate platform. The
[release procedure](releasing.md) requires a green manifest bound to the
candidate SHA before publication. A candidate is not a release: it must not be
tagged or announced until the same-SHA CI, archive-only cold install, frozen
external conformance, strict VM and performance gates are executed for that
SHA. The release records below refer to their tagged binaries.
minimum. Linux x86_64 on glibc 2.39 is the supported platform. The rc.4
manifest is green on its SHA with the documented strict-VM PASS and a
maintainer-approved shared-node performance `WARN`; stable/LTS still requires a
dedicated fixed node. The release records below refer to their tagged binaries.
## Current protocol integration
@@ -73,7 +75,48 @@ The `spec/` tree contains only current contracts; retired specifications are in
Git history and tagged archives. The earlier release records below describe
their tagged binaries and are not current protocol claims.
## 0.10 Closed public Analysis boundary — issue #10 (RC.4 candidate)
## 0.11 Explicit stdlib Bundle input — issue #11 Phase A (unreleased)
Phase A lands the build-input boundary only: the stdlib production sources and
the debug source fallback are still in this repository, and Phase B (the
ecosystem-assembled Bundle, source removal and `std:` replacement) is **not**
claimed. Executed candidate:
`ab6b6b1a23ec064fbc7de943c52befca18142a56`; bundle source commit
`2cbde54602c07f62a62f341400bc9cb4764a93f8`.
* `tools/stdlib/bundle-pin.json` pins `marqdo-stdlib@0.1.0` with tree digest
`sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713`
and alias digest
`sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb`;
`tools/stdlib/bundle.py` is the single resolver/verifier.
* `tools/pack-stdlib.py` and `tools/release/package.py` require
`--stdlib-dir` and accept `--bundle-pin`. A missing directory, missing
manifest, tree/alias digest mismatch, pin mismatch or symlink fails before
an archive is written; `RELEASE_INFO.json.stdlib.source` records the pinned
kind/repository/commit/path.
* Product, performance and release lanes resolve that Bundle
(`crates/cli/tests/support/stdlib.rs`, `tools/perf/runner.py`). An explicit
`MARQDO_TEST_STDLIB_BUNDLE`/`--stdlib-dir` changes the location but must match
the pin; a bad override fails even when the default is valid. Loader unit
tests build small synthetic Bundles.
* `tools/ci/independent_build.py` exports a clean copy without `stdlib/`,
builds `marqdo-cli` + `marqdo-provider-worker` with `--locked`, runs the
language-only `tests/independent/language-only.mq.md`, and requires a
stdlib-dependent run to fail closed with no sibling `stdlib/`. GitHub and
Woodpecker run the lane.
* Archive smoke and cold-install keep the missing-Bundle failure and now also
require the language-only `factorial` call to succeed after the shipped
`stdlib/` is moved aside. Two packaging runs from the same input and
toolchain are byte-identical.
Evidence:
[`evidence/2026-11-26-issue-11-phase-a.md`](evidence/2026-11-26-issue-11-phase-a.md).
Runtime discovery is unchanged: `MARQDO_STDLIB_DIR` (invalid values still fail
hard), then `stdlib/` next to the executable, then the debug-only source
fallback. Phase B is gated on ecosystem issue #2 and the extension replacement
evidence named by issue #11.
## 0.10 Closed public Analysis boundary — issue #10 (RC.4 released)
The candidate replaces the program-only Analysis projection in place under
[ADR-0069](adr/0069-public-analysis-boundary.md): exact source and document
@@ -107,17 +150,18 @@ Local development-container performance against the rc.3 archive binary on a
`--emit` `1.210 / 1.186`, `--refs` `1.145 / 1.093`. These are smoke numbers,
not a dedicated-node G4 result.
Same-SHA CI ([pipeline #89](https://ci.cflmy.cn/repos/1/pipeline/89)) is PASS
for the candidate code SHA `e0645f3` on all four lanes, and the follow-up
CI/tooling tree `b1fc211` is fully green in
[pipeline #91](https://ci.cflmy.cn/repos/1/pipeline/91); its build lane packaged the archive, ran the
archive smoke and the frozen extension suite 7/7. A local same-SHA archive
passed smoke and the archive-only Ubuntu 24.04 cold-install container, and the
frozen suite passed 7/7 from a clean worktree. The gate aggregate is
[`evidence/ci/e0645f376b03e31e342a6d3fb749a335f0840d1b/manifest.json`](evidence/ci/e0645f376b03e31e342a6d3fb749a335f0840d1b/manifest.json)
and decides `DO_NOT_RELEASE`: the RC profile still requires a same-SHA strict
VM PASS and an approved G4 node result, neither of which is available here. The
rc.3 rows below remain the last published release evidence.
Same-SHA CI ([pipeline #94](https://ci.cflmy.cn/repos/1/pipeline/94)) is PASS
for `452e9a3` on all four lanes; its build lane packaged the archive, ran smoke
and the frozen extension suite 7/7. The local same-SHA archive passed smoke,
the archive-only Ubuntu 24.04 cold-install container and frozen conformance
7/7. Strict L1 PASS is recorded from a disposable QEMU/TCG VM as non-root
`dev` (uid 1000), with the archived binary re-verified in that VM. Performance
is a maintainer-approved shared-node `WARN` for this RC only; stable/LTS still
requires a dedicated fixed node. The gate aggregate is
[`evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json`](evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json)
(`RC_RELEASE_CANDIDATE`). Release
[notes and assets](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-rc.4).
Downstream migration issues: `marqdo-view#6`, `marqdo-lint#4`.
## 0.9 Pre-stable protocol convergence — issue #8 (RC.3 candidate)
@@ -353,6 +397,9 @@ ownership / core resource kinds), ADR-0063 (foreign F-A). Executed evidence:
recompute both digests with the runtime algorithm and fail on mismatch; smoke
removes the bundle and requires a fail-closed run (no source fallback). Release
discovery only falls back to the compile-time source tree in debug builds.
Since issue #11 Phase A the Bundle is one required explicit build input
(`--stdlib-dir`) with a pinned identity and a recorded source commit
(ADR-0070); see §0.11.
- **H-04 core resource kinds:** `marqdo_host::CORE_RESOURCE_KINDS` is the single
registry used by the CLI manifest validator and every trusted host registration
path; all six core kinds are rejected as a provider name and as a declared kind
@@ -680,9 +727,11 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
routed to the bundled stdlib (Compat-C, ADR-0030/0031); there is no legacy
host formatter. `tools/pack-stdlib.py` additionally emits a byte-deterministic
offline archive + descriptor as an extraction-ready artifact
([evidence](evidence/2026-11-20-stdlib-package.md)). The stdlib intentionally
stays in this repository for now (ADR-0039); extraction is a future option
when size/release cadence requires it, not a pending gate.
([evidence](evidence/2026-11-20-stdlib-package.md)). Issue #11 Phase A now
consumes the Bundle through one explicit `--stdlib-dir` and one pinned
identity (ADR-0070, §0.11); the production sources still stay in this
repository until Phase B, which is gated on ecosystem issue #2 and the
extension replacement evidence.
- Resource streams (RFC-CM CM-A06, ADR-0025/0026/0040): opaque host-issued
`Resource` handles with `resource.open/read/write/close`; bytes move only
through `Memory`; stdin is read-only over one shared run cursor; stdout and
@@ -700,7 +749,8 @@ This is still a **local VM lane**, not a self-hosted GitHub Actions security URL
pins the workspace graph, `marqdo-runtime -> marqdo-host`, the bundled stdlib
digest and the stdio/file/TCP endpoints; `crates/cli/tests/stdlib_product.rs`
runs every public stdlib module (`clock/compress/console/csv/datetime/demo/env/format/fs/http/io/json/path/process/random/regex/stream/table/text/utf8`)
through `std:` imports over `stdlib/tests/*.mq.md`. `tools/pack-stdlib.py`
through `std:` imports over `stdlib/tests/*.mq.md` resolved from the pinned
Bundle (`crates/cli/tests/support/stdlib.rs`). `tools/pack-stdlib.py`
now sorts `.mq.md` by the same relative path key as the CLI. Source/test baseline
`0d40de7`; later docs-only commits keep code/test bytes identical. Evidence:
[`docs-and-test-migration`](evidence/2026-11-21-docs-and-test-migration.md).
@@ -0,0 +1,123 @@
# ADR-0070 — One explicit stdlib Bundle build input (Phase A)
Status: **Accepted for implementation on the 3.0 prerelease line** (2026-11-26).
Relates to: issue
[#11](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11), ADR-0028 (bundled
stdlib and `std:` imports), ADR-0039 (deferred extraction), ADR-0058 (public
aliases), ADR-0062 (resource ownership), ADR-0068 (single current public
contracts).
Evidence:
[`docs/evidence/2026-11-26-stdlib-source-coupling-inventory.md`](../evidence/2026-11-26-stdlib-source-coupling-inventory.md).
## Context
Issue #11 starts the extraction that ADR-0039 deferred: the CLI and the
Provider Worker must build and run on their own, while a release is assembled
from one explicitly provided, verifiable stdlib Bundle. The extraction trigger
listed by ADR-0039 is now real: an ecosystem repository pins component commits
and assembles the production Bundle, and nine component repositories own module
sources.
At the implementation baseline `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` the
stdlib source directory is implicit in four different ways, documented in the
inventory linked above:
* both packaging entry points read the checkout's `stdlib/` with no build
argument (`tools/pack-stdlib.py`, `tools/release/package.py`);
* product tests, the semantic harness and the P2 closure lane rebuild
`repo_root()/stdlib` independently;
* the performance runner silently falls back to `ROOT / "stdlib"` when the
binary has no sibling bundle;
* the debug CLI resolves a compile-time source tree
(`CARGO_MANIFEST_DIR/../../stdlib`) after the explicit override and the
sibling directory.
Separating compile, package and product-test lanes later requires changing all
of them at once, and none of them records which Bundle commit produced a test
run. The runtime contracts themselves — `stdlib.json`, the
`marqdo.stdlib-package` descriptor, Analysis `project.stdlib` and Observation
identity — are not the problem and must not change.
## Decision
### 1. Explicit build input
`tools/pack-stdlib.py` and `tools/release/package.py` accept the same required
`--stdlib-dir PATH` argument. It names an unpacked Bundle root that contains
`stdlib.json`. There is no implicit default: a missing path, a missing manifest,
a tree-digest mismatch, an alias-digest mismatch or a missing required module
fails the command before any archive is written. Both entry points keep the
existing deterministic archive layout, descriptor fields, digest algorithms
and checksums.
Both entry points also accept an optional `--bundle-pin PATH`. When given, the
input must match the pinned identity and the release record names the pinned
source commit; the pin is not a substitute for verifying the Bundle's own
manifest.
### 2. One pinned Bundle identity
`tools/stdlib/bundle-pin.json` records the Bundle name, version, source
repository and commit, tree digest and alias digest. `tools/stdlib/bundle.py`
is the single resolver and verifier for source-side consumers: tests, the
performance runner and release CI resolve the Bundle through it instead of
concatenating `stdlib/`.
An explicit `MARQDO_TEST_STDLIB_BUNDLE` (tests) or `--stdlib-dir` (tools) takes
precedence over the pin's default location, but the input must still verify
against the pin's digests. An invalid explicit input fails even when a valid
sibling Bundle exists; silent fallback is forbidden. Phase B updates the pin to
the Bundle assembled by the ecosystem repository; the algorithm does not change.
### 3. Runtime contract unchanged
`MARQDO_STDLIB_DIR` remains the explicit runtime override (invalid values fail
hard), followed by `stdlib/` next to the executable. The debug-only
compile-time source fallback remains in Phase A so the development loop keeps
working; it is removed in Phase B together with the in-repo production sources.
`stdlib.json`, `marqdo.stdlib-package`, Analysis `project.stdlib`, module ids
and Observation identity keep their current shapes and values.
### 4. Separated test lanes
The lanes become explicit:
* **independent compilation** — `cargo build --locked -p marqdo-cli
-p marqdo-provider-worker` in a copy without `stdlib/`, then a language-only
program through the real CLI;
* **loader unit tests** — small synthetic bundles built in a temporary
directory, so loader logic does not depend on the product tree;
* **product tests** — the whole pinned Bundle through `std:` and the real CLI;
* **conformance** — the frozen, independent fixture corpus, unchanged.
### 5. Phase B gate
Phase B (switch to the ecosystem-assembled Bundle, delete the in-repo
production sources, the debug source fallback and the replaced `std:` entries)
requires the accepted component commits of ecosystem issue #2 and the extension
replacement evidence named by issue #11. This ADR records the Phase A input
boundary only; it does not authorize deleting sources or changing `std:`
semantics.
## Consequences
* A packaging run can be pointed at a downloaded or separately built Bundle and
still produce the same deterministic archive and `RELEASE_INFO.json` record.
* Every product/perf CI run names the Bundle commit and digest it used; a
stale Bundle is visible instead of implicit.
* Phase B becomes a pin/CI change plus source removal, not a simultaneous
rewrite of the test lanes.
* The repository still carries the Bundle in Phase A, so the extraction is not
claimed as complete. `docs/STATUS.md` must record the Phase A state, not the
final externalized state.
## Non-goals
* Changing `std:` spelling, digest algorithms, module ids, public aliases or
the `stdlib.json`/descriptor shapes.
* Fetching a Bundle over the network, adding a package registry or a signature
scheme.
* Removing the debug source fallback, the in-repo `stdlib/` sources or any
`std:` entry in Phase A.
* Declaring the extraction, the external Conformance suite or the ecosystem
switch done before their evidence exists.
+3
View File
@@ -70,3 +70,6 @@ Files: `0001`–`0050`, plus:
pre-stable public boundary, replaced in place;
* [0069](0069-public-analysis-boundary.md) — one public Analysis projection for
independent document, lint and knowledge consumers.
* [0070](0070-explicit-stdlib-bundle-build-input.md) — Phase A of the stdlib
extraction: one required `--stdlib-dir` build input, one pinned Bundle
identity for tests/perf/release CI; runtime contracts unchanged.
+7 -4
View File
@@ -4,7 +4,7 @@ Status: **current architecture overview**. This file summarises the tree as it
is today. It is not a release promise, does not reopen a frozen ADR, and does not
replace `spec/` or a recorded test log.
- Baseline: `1e2a045cc78bf40972181abb44e7117c56cf4401` (2026-11-24, tagged `v3.0.0-rc.3`; same-SHA evidence in `../STATUS.md` and `../evidence/ci/1e2a045cc78bf40972181abb44e7117c56cf4401/manifest.json`). The `3.0.0-rc.4` candidate state is recorded in `../STATUS.md` §0.10.
- Baseline: `452e9a32bd9e40dba427d4180691c58bab74449e` (2026-11-25, tagged `v3.0.0-rc.4`; same-SHA evidence in `../STATUS.md` and `../evidence/ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json`).
- Normative behavior: `spec/`; frozen decisions: `docs/adr/`; executed evidence: `docs/STATUS.md` and `docs/evidence/`.
- This is the **single current overview**. Do not add a second running "current state" file;
update this file, `docs/STATUS.md` and an evidence file together.
@@ -140,8 +140,11 @@ Layer rules:
or a third-party plugin path.
2. The platform layer owns I/O, clocks, entropy, sockets and file handles. It must
not own JSON parsing, text formatting or memory allocation policy.
3. The stdlib is `.mq.md` and ships in this repository. New ordinary algorithms
go to `stdlib/` + tests + docs; they do not become Rust builtins.
3. The stdlib is `.mq.md` and ships in this repository during Phase A of
issue #11. New ordinary algorithms go to `stdlib/` + tests + docs; they do
not become Rust builtins. Packaging and product tests take it as one
explicit, pinned Bundle input (ADR-0070); Phase B moves the production
sources to the ecosystem assembly after issue #2 acceptance.
4. The CLI selects inputs, resolves configuration, assembles the host and routes
human/machine output. It is not a semantic policy centre.
5. Callable Plugin and Resource Provider share one registry/authorization/audit
@@ -229,7 +232,7 @@ that a phase is complete.
| Priority | Gap | State |
|---|---|---|
| P0 | **Language syntax migration**: RFC-LANG-0002 single contract | **closed at `9c1723d`**; implementation, stdlib digest, examples and fixtures green; platform/strict evidence remains separate |
| P0 | Stdlib release is a bundle in this repo; extraction is deferred (ADR-0039) | accepted, keep in repo |
| P0 | Stdlib extraction (issue #11): explicit `--stdlib-dir` + one pinned Bundle for tests/perf/release CI | **Phase A implemented** (ADR-0070); Phase B (ecosystem assembly, source removal) waits on ecosystem issue #2 and the extension replacement evidence |
| P0 | Documentation drift between `STATUS.md`, the architecture index and the evidence | being fixed by this migration and the docs gate |
| P1 | `std:fs/file` read/write/copy, metadata/directory, append/read_at/walk are implemented; watch and binary offset reads remain open | open |
| P1 | No file watch or binary `read_at` | open; future Resource Operation extension |
+18 -3
View File
@@ -14,8 +14,10 @@
The default Docker pipeline runs on push and pull request. A fast `contract`
lane exercises the public Analysis/Observation contracts through the real CLI
and the independent Python consumers; the full `test` lane runs the Rust gates
and the Windows cross-target compile check; `build` packages the archive, runs
the from-archive smoke and the frozen external conformance suite.
and the Windows cross-target compile check; `independent-build` exports the
commit without `stdlib/` and proves both shipped binaries still build and run a
language-only program; `build` packages the archive from the pinned stdlib
Bundle, runs the from-archive smoke and the frozen external conformance suite.
```text
contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries):
@@ -26,21 +28,29 @@ contract (rust:1.100-bookworm, python3-jsonschema, both shipped binaries):
stale-Analysis rejection
test (rust:1.100-bookworm, clippy/rustfmt, Node.js 22, MinGW, both binaries):
python3 tools/stdlib/bundle.py (verify the pinned Bundle)
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo build --locked -p marqdo-provider-worker
cargo test --workspace --locked
docs_consistency / architecture_boundaries / stdlib_product
stdlib_product again with MARQDO_TEST_STDLIB_BUNDLE + MARQDO_TEST_BUNDLE_PIN
python3 -m unittest discover -s tools/ci -p "test_*.py"
rustup target add x86_64-pc-windows-gnu
cargo check --workspace --all-targets --target x86_64-pc-windows-gnu
independent-build (rust:1.100-bookworm, git, python3):
git archive HEAD, remove stdlib/, no ecosystem checkout
cargo build --locked -p marqdo-cli -p marqdo-provider-worker
language-only check/call through the built CLI
stdlib-dependent run must fail closed; no stdlib/ next to the binary
minimum-rust (rust:1.89-bookworm):
cargo check --locked --workspace --all-targets
build (depends on test, minimum-rust, contract):
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
package the deterministic archive for $CI_COMMIT_SHA
python3 tools/stdlib/bundle.py; package --stdlib-dir stdlib --bundle-pin ...
from-archive smoke (tools/release/smoke.py)
frozen external conformance (tools/ci/run_frozen_extensions.sh, 7/7)
```
@@ -93,6 +103,11 @@ syntax; Debian bookworm's Node 18 fails those tests.
workspace tests so the provider CLI tests use the real helper, and adds a
`cargo check --workspace --all-targets --target x86_64-pc-windows-gnu`
compile gate (native Windows/macOS runtime lanes stay on the GitHub matrix).
* **ADR-0070 explicit Bundle:** the `test` lane verifies
`tools/stdlib/bundle-pin.json` and runs the product suite once with an
explicit `MARQDO_TEST_STDLIB_BUNDLE`; the new `independent-build` lane builds
both binaries from a copy without `stdlib/` and requires the stdlib-dependent
program to fail closed.
* The Woodpecker **build** lane and the GitHub **release-candidate** lane build
`marqdo` **and** `marqdo-provider-worker` and package both as siblings; the
provider transport resolves only that sibling (no PATH fallback), so an
+255
View File
@@ -0,0 +1,255 @@
# Public Analysis consumers after issue #10
Applies to `marqdo.analysis` revision 3 as defined by
[ADR-0069](../adr/0069-public-analysis-boundary.md), [spec/analysis.md](../../spec/analysis.md)
and [the schema](../../spec/schemas/analysis.schema.json). This page is the
integration guide for downstream static tools, in particular `marqdo-lint` and
`marqdo-view`.
The revision number did not change, but the shape did. An old revision-3
artifact is **not** accepted: current required fields are missing, and the
current schema and consumer semantics reject it. Rebuild the artifact and
update the consumer; do not add a compatibility reader or a second Analysis
shape.
## 1. What the CLI already provides
Run one command per program entry:
```sh
marqdo check path/to/index.mq.md --emit analysis.json
```
The artifact contains everything a document/lint/knowledge reader needs, from
the same static preparation as `check`, `inspect`, `run` and `call`:
- exact UTF-8 `modules[].source` and its SHA-256 `source_digest`;
- the Markdown AST in `modules[].document`;
- heading scopes in `modules[].units` and anchors in `modules[].anchors`;
- functions, imports, calls and resources;
- Markdown references with explicit resolution states;
- project context: `entry_module_id`, `identity_kind`, `root_id`,
`manifest_digest`, captured `lock_digest`, stdlib and extension identities;
- deterministic diagnostics.
`inspect --ast` and `inspect --units` now project the **same** AST and unit
shape. They remain human/debug selections; a machine consumer should read
`check --emit` and stop running a second `inspect --ast` process per module.
## 2. Required consumer changes
### 2.1 Read the source from the artifact
`modules[].source` is the exact text the loader read. Every span is a half-open
UTF-8 byte offset into that string.
- Do not reopen the file from `relative_path` for spans or digests; package
caches, stdlib and dependencies have no stable consumer-facing physical path.
- Verify `sha256(source.encode("utf-8")) == source_digest` before trusting a
span.
- `relative_path` remains package-relative and useful for display and project
layout, not for reconstructing an absolute path.
### 2.2 Document AST
`modules[].document` is the public AST described by
[`spec/markdown-profile.md`](../../spec/markdown-profile.md). Every node has
`kind`, `span` and `children` (`[]` for leaves); attributes/literals follow the
profile. The root `document` span now covers the whole source, including a BOM.
- Parse `document` directly; do not parse Markdown again for program
annotations.
- Renderers may keep their own rendering parser, but any *semantic* decision
(executable region, heading scope, function ownership) must use Analysis.
- Literal payloads are not guaranteed byte-equal to their span (entities,
escapes and code whitespace are normalised).
### 2.3 Heading scope: `span` changed meaning
For every non-root unit:
| Field | Meaning |
|---|---|
| `heading_span` | The original heading AST node span. Use this to locate the heading itself. |
| `span` | **Complete section range** from the heading through the next heading of the same or higher level, or EOF. It includes child headings. |
| `path` | Canonical structured heading path. Do not split `id` to recover it. |
| `parent_id` | Nearest real ancestor unit; root is `null`. |
| `mode` | Effective `exec` or `knowledge`. |
| `mode_origin` | `explicit` (ATX declaration), `inherited`, or `default` for the root. |
| `mode_source_unit_id` | The unit that supplied the mode; self-or-ancestor. |
| `kind` | `root`, `namespace`, `function`, `knowledge`, `section`. |
| `function` | Owning function id for Exec sections; `null` otherwise. |
Do not infer section ends from the next heading's text or from the old
short-span assumption. Use `heading_span` for heading UI; use `span` for the
whole section body.
`anchors` is `[{anchor, unit_id}]`, sorted by anchor. Anchors are navigation
names, not identities; a missing anchor is not a missing document.
### 2.4 References: boolean `resolved` is gone
`modules[].references[]` now always carries:
```json
{
"source": "root:x@0.1.0::index.mq.md",
"source_unit": "root:x@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:x@0.1.0",
"candidate_path": "theory.mq.md",
"fragment": "formula",
"candidates": []
}
```
| `state` | Consumer meaning |
|---|---|
| `resolved` | Exact module/unit or explicitly verified local file. `target_kind` is `module` or `file`. |
| `not_loaded` | The loaded catalog did not cover the local candidate. It is **not** missing; do not auto-create it. |
| `missing` | A known catalog module lacks the fragment, or explicit `--refs` verification proved absence. |
| `ambiguous` | Multiple exact canonical-name candidates; `target_unit` is null and `candidates` lists them. Never choose the first. |
| `external` | External URI scheme. No network access; not an error. |
| `outside_scope` | Absolute/drive/UNC/file URI, or a package-root escape. Never read it. |
| `invalid` | Malformed URI/percent encoding/unsupported address. |
Ordinary Analysis resolves only the loaded program. If a consumer needs to
verify unimported local files, use the CLI's explicit check:
```sh
marqdo check entry.mq.md --refs --json
marqdo inspect entry.mq.md --refs --json
```
Do not use the `--refs` artifact as the Observation binding input: `--refs`
adds diagnostics and changes the exact bytes. Run/call bind to the ordinary
`check --emit` bytes with the same static options.
### 2.5 Calls, functions and resources
- `functions[]` still has `id`, `unit_id`, `local_name`, `namespace`, `span`,
`heading_span`, `signature`, `effects`, `body`.
- `calls[]` now has `target_kind`, `target_owner` and `reason`. A plugin target
names the static owner (package/digest); it is never a Marqdo function.
`unresolved` with `reason: dynamic|unbound` is honest, not an error.
- `resources[]` carries `display: null` for code and a boolean for formulas;
verify its `content_digest` against the AST payload if you need integrity.
- The schema is closed: unknown required kinds/fields must be rejected, not
ignored.
### 2.6 Project context and freshness
- Load `project.entry_module_id`; it must occur once in `modules`.
- `root_id` is a logical manifest identity or a content snapshot, not a
cross-project permanent id.
- `manifest_digest` and `lock_digest` are the captured bytes; a changed file on
disk means a new check, not a retry of the old artifact.
- Verify the exact bytes with the published JSON Schema + semantic checks; keep
rejecting stale artifacts whose `source_digest` no longer matches the source
you display.
## 3. `marqdo-view` integration
Current View behavior to replace:
1. It runs `check --json --emit` and separately calls `inspect --ast --json`
per document. Replace the machine path with one `check --emit`; the AST is
`modules[].document`. Keep `inspect` only for human debug output.
2. It re-reads files and compares `source_digest`. Prefer `modules[].source`
directly; if it must use its own file snapshot, compare the artifact digest
and reject a mismatch.
3. Its `RawProject` ignores new required fields. Make
`entry_module_id`, `manifest_digest` and `extensions` required (or validate
with the schema) and remove the v2 acceptance branch. View must accept only
the current revision-3 shape.
4. `RawUnit.span` now means the complete section. For annotation placement use
`heading_span`; for source highlighting use the complete `span`.
5. `RawReference` already reads `state`; remove any remaining `resolved`
boolean mapping and map `not_loaded` as *unverified*, not as a broken link.
For a local candidate the View catalog does not know, show "未加载/未核验";
only `missing`/`ambiguous`/`invalid`/`outside_scope` are actionable errors.
6. Keep validating `source.analysis_digest` for Observation binding. The digest
remains SHA-256 of the exact `--emit` bytes; `--refs` diagnostics change it.
Suggested request/render flow:
```text
check --emit -> verify schema + source_digest -> document AST
-> units (complete span + heading_span) for annotations
-> references (state) for link presentation
-> calls/functions for executable markers
run/call + observation -> verify analysis_digest == sha256(artifact bytes)
```
## 4. `marqdo-lint` integration
Current Lint behavior to replace:
1. It performs one `inspect --ast` per module and then matches it with
Analysis. Use `modules[].source` and `modules[].document` from the same
`check --emit`; this removes a second process and any AST/span drift.
2. Its `AnalysisModule` model only requires the old fields and silently ignores
the new ones. Make `source`, `document`, `anchors` and the new unit fields
required; reject old same-revision artifacts. Prefer generating types from
the published schema rather than `Vec<Value>` for units/references.
3. Heading-boundary rules must use `units[].span` as the complete section and
`heading_span` as the heading itself. This is the authoritative range; do
not infer boundaries from Markdown siblings.
4. Link/reference lint: iterate `references[].state`. Report:
- `missing`/`ambiguous`/`invalid`/`outside_scope` as errors with
`source_unit` + `span`;
- `not_loaded` as an honest "unverified" notice, not a broken reference;
- `external` as informational.
Use the explicit `check --refs --json` run only when the user asks to verify
direct unimported targets.
5. `calls[]` can report static call targets and dynamic/unbound reasons; do not
infer a target from the display string. Plugin/builtin targets are not
Marqdo functions.
6. Continue using `--json` for diagnostic summaries; `--emit` is the only full
Analysis producer.
Suggested lint flow:
```text
check --emit -> verify schema + semantic invariants
-> per module: document + units(full span/heading_span)
-> rules: narrative/executable boundaries, calls, links, docs
-> diagnostics projected from Analysis + local rules
```
## 5. Shared rules for both consumers
- One current contract. Do not add a v2/v3 reader, field probing, fallback AST
from a second parser, or `try old shape then new shape`.
- Reject malformed/old artifacts with a corrective message: regenerate with the
current CLI, reinstall the Tool manifest, rebuild the consumer.
- Tool manifests keep `requires.analysis: 3`; the revision is unchanged, so
reinstall/rebuild is required because the old same-revision bytes are
rejected by the current schema.
- No private Rust crate, no `inspect --ir`, no package-cache path, no writing
to the analyzed project.
- The source in Analysis may contain secrets from the document. Do not log or
upload it by default; store artifacts with owner-only permissions.
- Keep the three independent fixture flows green: document rendering, lint with
diagnostics, and multi-entry knowledge linking.
## 6. Verification commands
On the current CLI:
```sh
marqdo check entry.mq.md --emit analysis.json
python3 tests/consumers/validate_protocols.py analysis.json observation.json tool.json
python3 tests/consumers/analysis_consumer.py analysis.json
marqdo inspect entry.mq.md --refs --json
```
For a downstream checkout, pin the CLI archive and run its real fixtures
against `MARQDO_BIN`; record the CLI SHA and the Analysis schema hash in the
consumer's evidence. See the issue accompanying this document for the exact
downstream acceptance items.
@@ -10,7 +10,8 @@
[ADR-0068](../adr/0068-single-current-public-contracts.md)
- **Contract:** `spec/analysis.md`, `spec/schemas/analysis.schema.json`
- **Gate manifest:** [`ci/e0645f376b03e31e342a6d3fb749a335f0840d1b/manifest.json`](ci/e0645f376b03e31e342a6d3fb749a335f0840d1b/manifest.json)
(`DO_NOT_RELEASE`: strict VM UNVERIFIED and no approved G4 node)
(`RC_RELEASE_CANDIDATE`: strict VM PASS; shared-node performance WARN
approved for this RC only)
This document records commands actually executed on the candidate tree. The
raw command log is
@@ -107,15 +108,14 @@ numbers and must not be cited as the dedicated-node G4 result.
## Release decision
`DO_NOT_RELEASE` for rc.4. The code/contract/CI/archive/conformance gates pass,
but the RC profile still requires a same-SHA strict-field PASS on a disposable
VM (this development container cannot create namespaces) and an approved
dedicated/shared-node G4 result. Neither is recorded for this SHA, so no tag,
archive publication or release claim is made.
`RC_RELEASE_CANDIDATE` for rc.4. A same-SHA disposable QEMU/TCG VM PASS
(uid 1000, `container: none`) and a maintainer-approved shared-node
performance `WARN` were recorded after this local gate. The tag and release are
`v3.0.0-rc.4` at `452e9a32bd9e40dba427d4180691c58bab74449e`; see
[`2026-11-25-rc.4-release.md`](2026-11-25-rc.4-release.md).
## Not claimed
- No disposable-VM strict L1 evidence for this SHA.
- No approved dedicated-node G4 measurement (the local comparison above is
smoke evidence only).
- No dedicated-node G4 PASS; the shared-node WARN is RC-only and does not
extend to stable/LTS.
- No Windows/macOS support claim.
@@ -1,10 +1,10 @@
你好,Marqdo
checked 2 module(s): ok
checked 1 module(s): ok
6
warning[sem.inferred_signature]: /tmp/marqdo/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/examples/math-library/index.mq.md:5:1: function signature was inferred; declare it with `params(...)`
## @exec 最大公约数
^
6
warning[sem.inferred_signature]: /tmp/marqdo/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/examples/factorial.mq.md:3:1: function signature was inferred; declare it with `params(...)`
## @exec 阶乘
^
@@ -1,6 +1,6 @@
From https://git.cflmy.cn/cflmy/marqdo-extension-conformance
* branch 015ff8ac15417b7ebbdb31ce2be2dab5362a1eba -> FETCH_HEAD
frozen CLI: /tmp/tmp.4rCUTQwVeO/install/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo sha256 a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e
frozen CLI: /tmp/tmp.IyNn1tzjCW/install/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/marqdo sha256 a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e
[PASS] plugin_worker: plugin check is static and succeeds
[PASS] plugin_worker: worker plugin executes three exports
[PASS] callable_registry: missing plugin export is symbol.unknown
@@ -1,7 +1,7 @@
{
"schema": "marqdo.extension-evidence",
"schema_version": 1,
"tested_sha": "e0645f376b03e31e342a6d3fb749a335f0840d1b",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"cli_binary_sha256": "a7306962689c635445a59043971ea2eb09298e01feeee81f0ba07b1f3e10306e",
"fixture_repo_sha": "015ff8ac15417b7ebbdb31ce2be2dab5362a1eba",
"os": "linux",
@@ -16,7 +16,7 @@
"negative_security": "PASS"
},
"commands": [
"python3 /tmp/tmp.4rCUTQwVeO/fixtures/tests/run_all.py (cwd=/tmp/tmp.4rCUTQwVeO/fixtures)"
"python3 /tmp/tmp.IyNn1tzjCW/fixtures/tests/run_all.py (cwd=/tmp/tmp.IyNn1tzjCW/fixtures)"
],
"failures": [],
"unverified": [],
+14 -52
View File
@@ -1,5 +1,5 @@
rc.4 final local gate 2026-11-25T03:40:44Z
source_sha: e0645f376b03e31e342a6d3fb749a335f0840d1b
rc.4 final local gate 2026-11-25T06:15:34Z
source_sha: 452e9a32bd9e40dba427d4180691c58bab74449e
platform: Linux 7.0.0-43-generic x86_64
rustc: rustc 1.100.0 (0ef1bc386 2026-11-09)
@@ -7,52 +7,14 @@ $ cargo fmt --all -- --check
PASS
$ cargo clippy --workspace --all-targets -- -D warnings
Compiling proc-macro2 v1.0.107
Checking serde_core v1.0.229
Checking zmij v1.0.23
Checking num-traits v0.2.19
Checking generic-array v0.14.7
Checking libc v0.2.191
Checking rustix v1.1.6
Checking crc32fast v1.5.5
Checking flate2 v1.1.11
Compiling phf_generator v0.14.0
Compiling quote v1.0.47
Compiling phf_codegen v0.14.0
Compiling comrak v1.0.0
Compiling syn v3.0.10
Checking block-buffer v0.10.4
Checking crypto-common v0.1.7
Checking num-integer v0.1.47
Checking digest v0.10.7
Checking sha2 v0.10.9
Checking getrandom v0.4.3
Checking getrandom v0.2.17
Checking ring v0.17.14
Checking tempfile v3.27.0
Checking serde_json v1.0.154
Checking rustls-webpki v0.103.17
Checking rcgen v0.13.2
Checking rustls v0.23.46
Compiling serde_derive v1.0.229
Compiling thiserror-impl v2.0.21
Compiling fearless_simd_macros v0.1.0
Compiling clap_derive v4.6.9
Checking memchr-n v0.1.10
Checking thiserror v2.0.21
Checking marqdo-worker-ipc v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-worker-ipc)
Checking marqdo-provider-worker v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-provider-worker)
Checking clap v4.6.9
Checking serde v1.0.229
Checking marqdo-span v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-span)
Checking num-bigint v0.4.8
Checking serde_yaml v0.9.34+deprecated
Checking marqdo-worker-ipc v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-worker-ipc)
Checking marqdo-sandbox v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-sandbox)
Checking marqdo-markdown v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-markdown)
Checking marqdo-package v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-package)
Checking marqdo-provider-worker v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-provider-worker)
Checking marqdo-value v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-value)
Checking marqdo-expression v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-expression)
Checking num-rational v0.4.2
Checking marqdo-markdown v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-markdown)
Checking marqdo-plugin-abi v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-plugin-abi)
Checking marqdo-foreign v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-foreign)
Checking marqdo-ir v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-ir)
@@ -61,7 +23,7 @@ $ cargo clippy --workspace --all-targets -- -D warnings
Checking marqdo-frontend v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-frontend)
Checking marqdo-runtime v3.0.0-rc.4 (/root/work/marqdo-cli/crates/marqdo-runtime)
Checking marqdo-cli v3.0.0-rc.4 (/root/work/marqdo-cli/crates/cli)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 8.53s
Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.36s
PASS
$ cargo test --workspace --locked
@@ -73,26 +35,26 @@ test result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; fin
$ cargo test -p marqdo-cli --test docs_consistency
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
$ cargo test -p marqdo-cli --test analysis_observation
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.34s
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.36s
$ cargo test -p marqdo-cli --test observation
test result: ok. 16 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 4.23s
test result: ok. 16 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 4.31s
$ cargo test -p marqdo-cli --test tool_protocol
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.09s
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.94s
$ cargo test -p marqdo-cli --test callable_resolution
test result: ok. 14 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.28s
test result: ok. 14 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27s
$ cargo test -p marqdo-cli --test heading_inheritance
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.07s
$ cargo test -p marqdo-cli --test conformance_ast
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
$ cargo test -p marqdo-cli --test conformance_semantics
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.69s
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.66s
$ cargo test -p marqdo-cli --test analysis_boundary
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 4.97s
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 4.98s
$ python3 -m unittest discover -s tools/ci -p test_*.py
Ran 43 tests in 0.092s
OK
$ cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
Finished `release` profile [optimized] target(s) in 0.05s
Finished `release` profile [optimized] target(s) in 0.24s
PASS
@@ -1,5 +1,5 @@
smoke: verified stdlib 0.1.0 tree=sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713 aliases=sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb files=42
smoke: archive version 3.0.0-rc.4, source e0645f376b03e31e342a6d3fb749a335f0840d1b
smoke: archive version 3.0.0-rc.4, source 452e9a32bd9e40dba427d4180691c58bab74449e
smoke: bundled stdlib missing -> fail-closed OK
smoke: strict unsupported on this host; fail-closed refused: {'reason': 'bubblewrap cannot create the required namespaces: bwrap: No permissions to create a new namespace, likely because the kernel does not allow non-privileged user namespaces. See <https://deb.li/bubblewrap> or <file:///usr/share/doc/bubblewrap/README.Debian.gz>.', 'state': 'unavailable'}
smoke: PASS
+62
View File
@@ -0,0 +1,62 @@
# RC 3.0.0-rc.4 release evidence — 452e9a32bd9e40dba427d4180691c58bab74449e
- **Date:** 2026-11-25
- **Product:** `3.0.0-rc.4` (prerelease; not stable, not LTS)
- **Source SHA:** `452e9a32bd9e40dba427d4180691c58bab74449e` (tag `v3.0.0-rc.4`)
- **Platform:** Linux x86_64, glibc 2.39 baseline; macOS/Windows UNSUPPORTED
- **Release archive:** `marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz`
sha256 `9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8`
- **Gate manifest:**
[`ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json`](ci/452e9a32bd9e40dba427d4180691c58bab74449e/manifest.json)
(`RC_RELEASE_CANDIDATE`)
- **Architecture:** [ADR-0069](../adr/0069-public-analysis-boundary.md),
[spec/analysis.md](../../spec/analysis.md)
- **Downstream guide:**
[`docs/developers/analysis-consumers.md`](../developers/analysis-consumers.md)
## Gates executed on this SHA
| Gate | State | Evidence |
|---|---|---|
| Same-SHA CI (`contract`, `test`, `minimum-rust`, `build`) | PASS | [pipeline #94](https://ci.cflmy.cn/repos/1/pipeline/94) |
| Frozen external conformance | PASS 7/7 | [`2026-11-25-rc.4-extension-manifest.json`](2026-11-25-rc.4-extension-manifest.json) |
| Archive-only smoke | PASS | [`2026-11-25-rc.4-release-smoke.log`](2026-11-25-rc.4-release-smoke.log) |
| Clean install: archive-only Ubuntu 24.04 container, non-root, no Cargo/network | PASS | [`2026-11-25-rc.4-cold-install.log`](2026-11-25-rc.4-cold-install.log) |
| Strict L1: disposable QEMU/TCG VM, non-root `dev` (uid 1000), image sha256 `7b9059…ecab9` | PASS | [`2026-11-25-rc.4-strict-evidence.json`](2026-11-25-rc.4-strict-evidence.json), [lane log](2026-11-25-rc.4-strict-lane.log) |
| Archived binary verified inside the same strict VM | PASS | [`2026-11-25-rc.4-strict-archive-verify.log`](2026-11-25-rc.4-strict-archive-verify.log) |
| Version compatibility (Rust 1.89 minimum, CLI/product, prerelease ranges) | PASS | pipeline #94 test lane |
| Shared-node performance | WARN (maintainer-approved for this RC only) | [`2026-11-25-rc.4-shared-node-performance.md`](2026-11-25-rc.4-shared-node-performance.md) |
| Windows / macOS | UNSUPPORTED | Linux-only RC scope |
The same-SHA CI build lane packaged its own archive
(`sha256 675ee7bdf4725e034f79ecf6d8609c1b667cb267f70df4ae686c023e8c5e3018`),
ran smoke and the frozen extension suite 7/7, and recorded CLI
`119b4d7d0431d8e958253add4b67a6ed826678b5254583d5320136b1b9a6e93b` and
provider worker `4e64bec9376c27e1b36cde510fd06159a86ae5d10f82f98137c2b8ba6ee7d908`.
## Behaviour changes since rc.3
Issue [#10](https://git.cflmy.cn/cflmy/marqdo-cli/issues/10) replaced
`marqdo.analysis` revision 3 **in place**:
- exact `source`/`source_digest`, public document AST, complete heading scopes
and anchors, entry/manifest/lock/stdlib/extension identities;
- one shared `document_refs` resolver used by Analysis, `check --refs` and
`inspect --refs`, with `resolved/not_loaded/missing/ambiguous/external/
outside_scope/invalid`;
- removed the duplicate `commands.rs` resolver and the post-preparation lock
re-read;
- `--emit` writes owner-only exclusive bytes atomically and refuses inputs,
directories, symlinks and hard links;
- independent schema + semantic consumers and mutation fixtures; old
same-revision artifacts are rejected.
Downstream `marqdo-view` and `marqdo-lint` must follow
[`analysis-consumers.md`](../developers/analysis-consumers.md); their tracking
issues are linked from the release announcement.
## What this evidence does not claim
Stable `3.0.0`, LTS, Windows/macOS support, strict L2, dedicated-node G4, or a
publisher signature. Checksums are integrity only. The shared-node performance
exception is scoped to this named RC and is not reusable for LTS.
@@ -0,0 +1,53 @@
# RC 3.0.0-rc.4 — shared-node performance evidence (WARN)
- **Date:** 2026-11-25
- **Product:** `3.0.0-rc.4`
- **Source SHA:** `452e9a32bd9e40dba427d4180691c58bab74449e`
- **Class:** shared-node `WARN`, **not** a dedicated-node G4 PASS
- **Approval:** the maintainer (`cflmy`) approved shared-node performance
evidence for this named RC on 2026-11-25. This exception is RC-only; a
stable/LTS release requires a dedicated fixed node.
- **Evidence generation:** `docs/evidence/2026-11-25-rc.4-analysis-boundary.md`
and the packed archives below.
## Environment
- Shared development host: Intel Core i7-8565U, 4 cores / 8 threads, 14 GiB RAM,
`powersave` governor, Linux `7.0.0-43-generic` x86_64, load average
`0.24 0.79 1.50` at sampling start.
- The agent runs in a container (`systemd-detect-virt --container` =
`container-other`); this is explicitly **not** a dedicated node and not a
QEMU/TCG VM. Its times are not comparable with the release G4 node.
- Baseline and candidate are the shipped release archives, five warmups and
twenty samples per command, same cwd and same fixture.
## Fixture
101 `.mq.md` modules, 82,094 bytes, 903 units, 100 cross-module references,
nested headings, paragraphs, formulas and code fences. The candidate emitted a
2,739,388-byte Analysis; the schema validator and independent
`analysis_consumer.py` accepted it (101 modules, 100 references).
## Results
| Command | rc.3 p50 / p95 (ms) | rc.4 p50 / p95 (ms) | p95 ratio | peak RSS ratio |
|---|---|---|---|---|
| `check index.mq.md --json` | 18.75 / 19.14 | 20.28 / 20.47 | 1.069 | 1.034 |
| `check index.mq.md --emit out.json` | 36.45 / 37.23 | 50.15 / 51.55 | 1.385 | 1.225 |
| `check index.mq.md --refs --json` | 20.07 / 20.33 | 23.65 / 24.05 | 1.183 | 1.107 |
Artifact size grew from 899,146 to 2,739,388 bytes because it now carries exact
source and the document AST. `--emit` p95 and peak-RSS ratios remain below the
issue's 2.5x budget; no-emit p95 is below 1.15x. `--refs` is a diagnostic
extension, not the ordinary no-emit execution path.
The candidate binary in this measurement is the same shipped rc.4 archive
(`sha256 9c3f166b5e5b8840d39d10019074e4e1c42432fc23e26c69670e64fdcf4e15d8`)
and the baseline is the published rc.3 archive. Correctness was verified before
accepting the timings.
## Limits
This is a `WARN` on a shared host. It must not be cited as a dedicated-node G4
PASS, and it does not extend to LTS. The RC gate manifest records the approval
reference and the `WARN` state.
@@ -0,0 +1,15 @@
Warning: Permanently added '[127.0.0.1]:2222' (ED25519) to the list of known hosts.
marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu.tar.gz: OK
SOURCE_SHA=452e9a32bd9e40dba427d4180691c58bab74449e
marqdo 3.0.0-rc.4
available
你好,Marqdo
warning[sem.inferred_signature]: /home/dev/rc4-install/marqdo-3.0.0-rc.4-x86_64-unknown-linux-gnu/examples/factorial.mq.md:3:1: function signature was inferred; declare it with `params(...)`
## @exec 阶乘
^
warning[sem.inferred_signature]: /project/factorial.mq.md:3:1: function signature was inferred; declare it with `params(...)`
## @exec 阶乘
^
factorial=120
checked 2 module(s): ok
analysis=marqdo.analysis 3 3.0.0-rc.4
@@ -0,0 +1,35 @@
{
"schema": "marqdo.strict-evidence.v1",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"tested_sha_source": "git-rev-parse",
"tested_sha_verified": true,
"source_archive_sha256": "sha256:3a6db40bb64779c932e101b97e83527669881a12a9c6639e9f694f71ec14fbcb",
"run": {
"command": "./tests/security/run-lane.sh",
"outcome": "PASS",
"runner_kind": "disposable-vm",
"run_url": "",
"runner_image_sha256": "sha256:7b90593f5532b49b7e3fe3d2743f0d1f0d822e5b07cebcd8e00c0df8069ecab9",
"lane_log": "/home/dev/evidence-452e9a32bd9e40dba427d4180691c58bab74449e/gc-lane.log",
"started_utc": "2026-11-25T06:03:57Z",
"finished_utc": "2026-11-25T06:05:19Z"
},
"environment": {
"uname": "Linux-7.0.0-43-generic-x86_64-with-glibc2.43",
"kernel": "7.0.0-43-generic",
"machine": "x86_64",
"cgroup2": "cgroup2 cgroup2 rw,nsdelegate,memory_recursiveprot,memory_hugetlb_accounting",
"container": "none",
"uid": 1000,
"user": "dev",
"root": false,
"bwrap_version": "bubblewrap 0.11.1",
"rustc": "rustc 1.100.0 (0ef1bc386 2026-11-09)",
"cargo": "cargo 1.100.0 (3acc79c0c 2026-11-05)",
"python": "3.14.4",
"cc": [
"cc (Ubuntu 15.2.0-16ubuntu1) 15.2.0"
],
"source_archive_sha256_matches": true
}
}
@@ -0,0 +1,47 @@
== adversarial helper matrix ==
Compiling marqdo-sandbox v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-sandbox)
Finished `test` profile [unoptimized + debuginfo] target(s) in 7.92s
Running tests/security_linux.rs (target/debug/build/marqdo-sandbox/05fde20fe9d1e50b/out/security_linux-05fde20fe9d1e50b)
running 7 tests
test strict_child_cannot_escape_via_proc_or_privileges ... ok
test strict_child_cannot_reach_the_network ... ok
test strict_child_cannot_read_host_files_but_reads_the_project ... ok
test strict_child_cannot_write_outside_or_into_the_project ... ok
test strict_child_identity_is_unprivileged_and_namespaced ... ok
test strict_supervisor_enforces_fd_and_process_limits ... ok
test strict_supervisor_enforces_memory_cpu_and_output_limits ... ok
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 10.54s
== build CLI ==
Compiling marqdo-span v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-span)
Compiling marqdo-worker-ipc v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-worker-ipc)
Compiling marqdo-sandbox v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-sandbox)
Compiling marqdo-package v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-package)
Compiling marqdo-value v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-value)
Compiling marqdo-expression v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-expression)
Compiling marqdo-markdown v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-markdown)
Compiling marqdo-foreign v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-foreign)
Compiling marqdo-plugin-abi v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-plugin-abi)
Compiling marqdo-ir v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-ir)
Compiling marqdo-host v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-host)
Compiling marqdo-frontend v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-frontend)
Compiling marqdo-runtime v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/marqdo-runtime)
Compiling marqdo-cli v3.0.0-rc.4 (/home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/crates/cli)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 34.76s
strict mechanism: bubblewrap 0.11.1 (user/mount/PID/net/UTS/IPC namespaces + no-new-privs + rlimits)
== positive CLI contract ==
warning[sem.inferred_signature]: /home/dev/marqdo-452e9a32bd9e40dba427d4180691c58bab74449e/examples/factorial.mq.md:3:1: function signature was inferred; declare it with `params(...)`
## @exec 阶乘
^
warning[sem.inferred_signature]: /project/factorial.mq.md:3:1: function signature was inferred; declare it with `params(...)`
## @exec 阶乘
^
== strict language resources are console-only ==
== external-execution surfaces are refused ==
== @knowledge payloads stay inert under strict ==
== forged active marker is rejected ==
G-C security lane: PASS
strict evidence: /home/dev/evidence-452e9a32bd9e40dba427d4180691c58bab74449e/strict-evidence.json
strict evidence: /home/dev/evidence-452e9a32bd9e40dba427d4180691c58bab74449e/strict-evidence.json
@@ -0,0 +1,195 @@
# Issue #11 Phase A — one explicit stdlib Bundle input
Date: 2026-11-26.
Implementation baseline: `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7`.
Bundle source commit: `2cbde54602c07f62a62f341400bc9cb4764a93f8`.
Decision: [ADR-0070](../adr/0070-explicit-stdlib-bundle-build-input.md).
Inventory:
[`2026-11-26-stdlib-source-coupling-inventory.md`](2026-11-26-stdlib-source-coupling-inventory.md).
Candidate commits (in order):
| Commit | Change |
|---|---|
| `b9c72e1` | ADR-0070 + source-coupling inventory |
| `1b9d9c4` | `tools/stdlib/bundle.py`, `bundle-pin.json`, required `pack-stdlib.py --stdlib-dir` |
| `422b9de` | `package.py --stdlib-dir/--bundle-pin`, `RELEASE_INFO.stdlib.source` |
| `3a68260` | pinned test resolver, synthetic loader tests, product/conformance rewiring |
| `ab6b6b1` | independent-build lane, perf Bundle pin, CI and docs |
| `0e1efc7` | archive smoke/cold-install keep the language-only run after removing the Bundle |
The documentation commit that adds this record also updates `STATUS.md`, the
architecture overview, `README.md` and `tests/README.md`. CI follow-up commit
`2acaaef` folds the `independent-build` job into the existing `linux` evidence
gate (the release-evidence schema accepts only its declared gate names).
Executed host: Linux x86_64 (glibc 2.43), `rustc 1.100.0 (0ef1bc386
2026-11-09)`, `cargo 1.100.0 (3acc79c0c 2026-11-05)`, Python 3.14.4; the
cold-install container is `ubuntu:24.04` (glibc 2.39) with `--network none`.
## 1. Pinned Bundle identity
```console
$ python3 tools/stdlib/bundle.py
{
"aliases_digest": "sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb",
"file_count": 42,
"name": "marqdo-stdlib",
"root": "<checkout>/stdlib",
"source_commit": "2cbde54602c07f62a62f341400bc9cb4764a93f8",
"tree_digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"version": "0.1.0"
}
```
`tools/stdlib/bundle-pin.json` records the same identity. The resolver accepts
an explicit location but never an explicit identity: a valid-but-unpinned
Bundle is rejected.
## 2. Failure paths (tools/ci/test_stdlib_bundle_tools.py)
64 `tools/ci` unit tests pass. The new cases cover:
* `--stdlib-dir` is required and a missing input fails before any output;
* a missing `stdlib.json`, a tree-digest mismatch, an alias-digest mismatch and
`public_aliases` without `aliases_digest` fail;
* a symlink inside the Bundle is rejected;
* an explicit Bundle that does not match the pin fails, even when the pinned
default is valid;
* a bad pin schema fails;
* the `bundle.py` CLI exits 1 on an invalid explicit input and 0 with
`--print-path` otherwise.
The runtime override rule is pinned by the loader unit test
`bad_override_fails_closed_even_with_a_valid_sibling` (a bad
`MARQDO_STDLIB_DIR` fails although a valid sibling `stdlib/` exists).
## 3. Deterministic packaging
Two standalone stdlib packs from the same explicit input and toolchain are
byte-identical:
```console
$ python3 tools/pack-stdlib.py --stdlib-dir stdlib \
--bundle-pin tools/stdlib/bundle-pin.json --out-dir <a>
$ python3 tools/pack-stdlib.py --stdlib-dir stdlib \
--bundle-pin tools/stdlib/bundle-pin.json --out-dir <b>
$ sha256sum <a>/marqdo-stdlib-0.1.0.tar.gz <b>/marqdo-stdlib-0.1.0.tar.gz
f6dc8e7ad92bc58b815635aea923069919d6f5495078e53828ae4723d925a565 <a>/marqdo-stdlib-0.1.0.tar.gz
f6dc8e7ad92bc58b815635aea923069919d6f5495078e53828ae4723d925a565 <b>/marqdo-stdlib-0.1.0.tar.gz
```
Two release archives built from `ab6b6b1` with `--skip-example-build` (the
host-built example artifacts were already present) are byte-identical:
`f37e01c44e668a6daf0538b32e9825cc74392f0ccbd65362af2783629b6d2c48`.
`RELEASE_INFO.json.stdlib.source` records
`{"kind":"in-repo","repository":"cflmy/marqdo-cli","commit":"2cbde54602c07f62a62f341400bc9cb4764a93f8","path":"stdlib"}`
and the tree/alias digests equal `stdlib.json`.
## 4. Product and performance lanes
The product, HTTP, table, alias-routing, P2 closure and semantic harnesses
resolve the pinned Bundle through `crates/cli/tests/support/stdlib.rs`
(`MARQDO_TEST_STDLIB_BUNDLE`/`MARQDO_TEST_BUNDLE_PIN` overrides are verified
against the pin). Loader unit tests build synthetic Bundles instead of the
product tree.
```console
$ cargo test -p marqdo-cli --bin marqdo stdlib --offline
4 passed (synthetic loader tests)
$ cargo test -p marqdo-cli --test stdlib_product --offline
16 passed
$ cargo test -p marqdo-cli --test stdlib_bundle --test stdlib_http \
--test stdlib_table --test stdlib_alias_routing --offline
13 passed
$ cargo test -p marqdo-cli --test architecture_boundaries \
--test conformance_semantics --test p2_closure --offline
16 passed
$ python3 tools/perf/runner.py --no-build --binary target/debug/marqdo \
--warmups 1 --samples 3 --allow-smoke --only hello-check ...
correctness=VERIFIED status=SMOKE
stdlib={... "source_commit":"2cbde54602c07f62a62f341400bc9cb4764a93f8" ...}
```
## 5. Independent build (clean copy without stdlib)
`tools/ci/independent_build.py` exported `ab6b6b1` with `git archive`, removed
`stdlib/`, and built both binaries with `--locked`:
```json
{
"status": "PASS",
"source_sha": "ab6b6b1a23ec064fbc7de943c52befca18142a56",
"binaries": {
"marqdo": {"sha256": "428c25c60caa7762348bcffad96558591adf52440d44549a645390c927558757"},
"marqdo-provider-worker": {"sha256": "3787942de6d35ce1c7f03c0848c8e08b6037495e98005c62704d34e664da795c"}
},
"checks": {
"stdlib_source_removed": true,
"language_only_check": "PASS",
"language_only_call": "PASS:3",
"stdlib_dependent_missing_bundle": "PASS",
"no_sibling_stdlib": true
}
}
```
The stdlib-dependent `run examples/hello.mq.md` failed with an explicit
stdlib/print diagnostic instead of falling back to a source tree; the built
`target/debug` directory contains no `stdlib/`.
## 6. Archive smoke and cold install
```console
$ python3 tools/release/smoke.py --archive <archive>
smoke: verified stdlib 0.1.0 tree=sha256:5407d36... aliases=sha256:5f513c0... files=42
smoke: archive version 3.0.0-rc.4, source ab6b6b1a23ec064fbc7de943c52befca18142a56
smoke: bundled stdlib missing -> fail-closed OK
smoke: language-only program runs without the bundled stdlib
smoke: PASS
```
```console
$ bash tools/release/cold-install.sh <archive> ab6b6b1a23ec064fbc7de943c52befca18142a56
你好,Marqdo
checked 2 module(s): ok
checked 1 module(s): ok
6
runtime error[kernel.unavailable]: 打印 requires the bundled stdlib print module; install the official CLI bundle
<language-only factorial call still prints 120>
```
The container is `ubuntu:24.04`, `--network none`, user `65534:65534`, with no
Cargo and no source checkout; only the archive bytes are mounted. Moving the
shipped `stdlib/` aside keeps the language-only factorial call working and
makes the `打印` program fail with the explicit `kernel.unavailable` message.
## 7. Gates on the candidate tree
```console
$ cargo fmt --all -- --check
FMT_OK
$ cargo clippy --workspace --all-targets --offline -- -D warnings
exit=0
$ cargo test --workspace --locked --offline
exit=0
634 passed, 0 failed, 2 ignored across 72 test binaries
```
The workspace run includes `docs_consistency` (7 passed),
`architecture_boundaries`, the frozen conformance suites and every product
lane. It was executed on the candidate tree plus this documentation change and
is reproducible with `cargo test --workspace --locked`. Platform-native
Windows/macOS runs were not re-executed for this docs-only candidate; the
existing GitHub matrix remains the lane for them.
## 8. Not claimed
* Phase B: switching to the ecosystem-assembled Bundle, removing the in-repo
production sources, removing the debug source fallback and deleting replaced
`std:` entries. It is gated on ecosystem issue #2 and the extension
replacement evidence named by issue #11.
* Any `std:`/`stdlib.json`/`marqdo.stdlib-package`/Analysis/Observation shape
change; none was made.
* A docker cold-install on a Windows/macOS host or a native Windows/macOS
product run for this candidate.
@@ -0,0 +1,72 @@
# Stdlib source-directory coupling inventory (issue #11, Phase A)
Date: 2026-11-26.
Implementation baseline: `4bbefc92449ee480c8a2c89b0308feb4cda8d0e7` (current
`master`). Bundle source commit: `2cbde54602c07f62a62f341400bc9cb4764a93f8`
(the last commit that touched `stdlib/` at the baseline). Pinned Bundle:
`marqdo-stdlib` `0.1.0`, tree digest
`sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713`,
alias digest
`sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb`.
This file inventories every direct reference to the checkout's stdlib source
directory found for issue #11 Phase A, before the explicit build-input change.
It is an inventory, not a claim that Phase A is finished; the executed evidence
is recorded separately when the work lands. Decision:
[ADR-0070](../adr/0070-explicit-stdlib-bundle-build-input.md).
## Packaging and release tooling
| Entry point | Reference | Phase A disposition |
|---|---|---|
| `tools/pack-stdlib.py` | `STDLIB = ROOT / "stdlib"` (line 17); used by the tree digest, manifest read, file list, archive and descriptor (lines 37–97) | required `--stdlib-dir`, optional `--bundle-pin`; shared digest/verify helper |
| `tools/release/package.py` | `STDLIB = ROOT / "stdlib"` (line 37); `verify_stdlib` (lines 110–141), staging copy (line 229), `RELEASE_INFO.stdlib` (lines 245–264) | required `--stdlib-dir`, optional `--bundle-pin`; `RELEASE_INFO.stdlib.source` records the pinned commit |
| `tools/release/smoke.py` | reads only the extracted archive's `install/stdlib` (lines 81–116) | unchanged; it stays an independent verifier of the shipped bytes |
| `tools/perf/runner.py` | pops `MARQDO_STDLIB_DIR`, then falls back to `ROOT / "stdlib"` when the binary has no sibling bundle (lines 327–330) | resolve the pinned Bundle explicitly and always export `MARQDO_STDLIB_DIR`; no silent repo fallback |
| `tools/ci/test_release_archive.py` | reads `ROOT/stdlib/stdlib.json` and `ROOT/stdlib` (lines 33, 40, 54) | pass the explicit/pinned path; add failure-path assertions |
| `.github/workflows/ci.yml` | `package.py` invocation without a Bundle argument (line 224); product lane (lines 44–45) | pass `--stdlib-dir` + `--bundle-pin`; verify the pin in the product lane |
| `.woodpecker/main.yml` | product lane (line 51), `package.py` invocation (line 80) | same as above |
| `.woodpecker/performance.yml` | `package.py` invocation (line 25) | pass `--stdlib-dir` + `--bundle-pin`; perf runner resolves the pin |
| `docs/releasing.md` | release command without a Bundle argument (line 119) | document the required input and the pin |
## Runtime and development discovery
| Entry point | Reference | Phase A disposition |
|---|---|---|
| `crates/cli/src/stdlib.rs` | debug-only `CARGO_MANIFEST_DIR/../../stdlib` fallback after `MARQDO_STDLIB_DIR` and the sibling directory (lines 73–82) | keep for the development loop; remove in Phase B |
| `crates/cli/src/stdlib.rs` unit tests | `dev_bundle()` loads the whole in-repo tree (lines 457–492) | replace with synthetic small bundles so loader tests do not depend on the product tree |
## Test harnesses that rebuild `repo_root()/stdlib`
| Harness | Reference | Role | Phase A disposition |
|---|---|---|---|
| `crates/cli/tests/stdlib_product.rs` | `stdlib_dir()` (lines 35–37), fixtures (line 48), cwd/`MARQDO_STDLIB_DIR` (lines 130–138) | product | pinned resolver |
| `crates/cli/tests/stdlib_bundle.rs` | `stdlib_dir()` (lines 19–20) | product | pinned resolver |
| `crates/cli/tests/stdlib_http.rs` | cwd and `MARQDO_STDLIB_DIR` (lines 22–23) | product | pinned resolver |
| `crates/cli/tests/stdlib_table.rs` | cwd and `MARQDO_STDLIB_DIR` (lines 21–22) | product | pinned resolver |
| `crates/cli/tests/stdlib_alias_routing.rs` | copies `repo()/stdlib` (lines 64–65) | product | pinned resolver |
| `crates/cli/tests/p2_closure.rs` | table self-test path, cwd and env (lines 112, 122–123) | product | pinned resolver |
| `crates/cli/tests/conformance_semantics.rs` | alias binding (line 294), entry `std:` imports (line 431) | conformance | pinned resolver |
| `crates/cli/tests/architecture_boundaries.rs` | in-repo digest/import gates (lines 90–114, 442–477) | architecture gate | pinned resolver plus the Phase A in-repo assertion |
## References that are intentionally not build inputs
* `crates/cli/src/analysis/*`, `crates/cli/src/loader.rs` and
`crates/cli/src/commands.rs` consume the verified `StdlibBundle` identity at
run time; they do not read the source directory.
* `crates/marqdo-runtime/src/builtins_impl.rs` and
`crates/marqdo-sandbox/*` mention stdlib only in diagnostics/tests.
* `docs/evidence/*` and historical ADRs keep their recorded paths; they are
decision history, not executable inputs.
## Acceptance for Phase A
1. A clean copy without `stdlib/` and without an ecosystem checkout builds
`marqdo-cli` and `marqdo-provider-worker` with `--locked`.
2. Both packaging entries fail without `--stdlib-dir`, and fail on a missing
directory, a missing `stdlib.json`, a tree-digest mismatch, an alias-digest
mismatch or a pin mismatch.
3. Product tests, the performance runner and release CI resolve the Bundle
through `tools/stdlib/bundle.py` and name its pinned commit and digest.
4. The frozen Conformance corpus and the independent `tools/release/smoke.py`
checks stay in place.
@@ -0,0 +1,59 @@
{
"schema": "marqdo.release-gates.v1",
"profile": "rc",
"target_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"recorded_utc": "2026-11-25T06:13:39Z",
"gates": {
"linux": {
"state": "PASS",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"run_url": "https://ci.cflmy.cn/repos/1/pipeline/94",
"recorded_utc": "2026-11-25T06:13:39Z"
},
"extension": {
"state": "PASS",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"run_url": "docs/evidence/2026-11-25-rc.4-extension-manifest.json",
"recorded_utc": "2026-11-25T06:13:39Z"
},
"clean_install": {
"state": "PASS",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"run_url": "docs/evidence/2026-11-25-rc.4-cold-install.log",
"recorded_utc": "2026-11-25T06:13:39Z"
},
"version_compat": {
"state": "PASS",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"run_url": "https://ci.cflmy.cn/repos/1/pipeline/94",
"recorded_utc": "2026-11-25T06:13:39Z"
},
"windows": {
"state": "UNSUPPORTED",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"run_url": "COMPATIBILITY.md",
"recorded_utc": "2026-11-25T06:13:39Z"
},
"macos": {
"state": "UNSUPPORTED",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"run_url": "COMPATIBILITY.md",
"recorded_utc": "2026-11-25T06:13:39Z"
},
"strict_vm": {
"state": "PASS",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"run_url": "docs/evidence/2026-11-25-rc.4-strict-evidence.json",
"recorded_utc": "2026-11-25T06:13:39Z"
},
"performance": {
"state": "WARN",
"tested_sha": "452e9a32bd9e40dba427d4180691c58bab74449e",
"run_url": "docs/evidence/2026-11-25-rc.4-shared-node-performance.md",
"rc_shared_node_approval": "Maintainer cflmy approved shared-node performance WARN for v3.0.0-rc.4 on 2026-11-25; docs/evidence/2026-11-25-rc.4-shared-node-performance.md",
"recorded_utc": "2026-11-25T06:13:39Z"
}
},
"release_decision": "RC_RELEASE_CANDIDATE",
"reasons": []
}
+15 -3
View File
@@ -4,6 +4,15 @@ Status: the sampler and correctness corpus are implemented; **no release
performance baseline exists yet**. Do not cite a development-container or
TCG/QEMU number as a release gate.
## Release-class policy
- **RC candidates** may use a maintainer-approved shared node. The environment,
load, limits, paired baseline/candidate comparison and approval are recorded
in the release notes; the result remains `WARN`, never a dedicated-node PASS.
- **Stable/LTS** releases require a dedicated fixed node and the full paired-run
protocol. The shared-node exception is RC-only and must not be reused for
LTS evidence.
## Three separate measurements
| Class | Goal | Host |
@@ -18,9 +27,12 @@ dominated by emulation and is not comparable with native or KVM.
## Tool
`tools/perf/runner.py` (schema `marqdo.perf.v2`) builds one release binary,
records its SHA256/Cargo.lock/rustc/source SHA, verifies every workload's exact
wire digest **before** timing, then reports warmups/samples, p50, p95, MAD,
CPU user/sys, peak RSS and the environment manifest. See
records its SHA256/Cargo.lock/rustc/source SHA, resolves one pinned stdlib
Bundle (name, version, tree/alias digests, source commit) and passes it to every
workload as `MARQDO_STDLIB_DIR`, verifies every workload's exact wire digest
**before** timing, then reports warmups/samples, p50, p95, MAD, CPU user/sys,
peak RSS and the environment manifest. A bad Bundle input or digest mismatch
fails before any workload runs; there is no checkout fallback (ADR-0070). See
[`tools/perf/README.md`](../tools/perf/README.md).
Rules enforced by the tool:
+24 -15
View File
@@ -75,17 +75,19 @@ Use the frozen-SHA build and archive checks above. Additionally:
- Strict L1 requires a same-SHA PASS on a disposable VM as a non-root user.
Record the strict evidence and verify the archived binary on that guest.
- Measure the packaged CLI on a dedicated fixed node with 5 warmups and
20 samples or more for each of the nine workloads. Compare against a
correctness-verified baseline on the same node, CPU affinity, governor,
kernel and toolchain. Record investigation and resolution for any p50
increase of at least 15% or median peak RSS increase of at least 20%.
A dedicated node is the default. For a prerelease approved by the
maintainer to use a shared node, take at least three paired beta/RC runs
under the same measured conditions and keep all reports. Verify all nine
workloads and investigate threshold breaches or unstable samples before
accepting a `WARN`. Record the approval, runner environment and limits in
the release notes. This exception applies to the named RC only.
- Measure the packaged CLI with 5 warmups and 20 samples or more for each of
the nine workloads, or for the changed boundary's representative fixture when
the gate is scoped by an accepted ADR. Compare against a correctness-verified
baseline on the same node, CPU affinity, governor, kernel and toolchain.
Record investigation and resolution for any p50 increase of at least 15% or
median peak RSS increase of at least 20%.
**RC candidates may use a shared node.** The maintainer approves the shared
node for that named RC, the environment/load/limits and the comparison are
recorded in the release notes, and the result stays a `WARN`; it is never
promoted to a dedicated-node PASS. A final stable/LTS release requires a
dedicated fixed node with the full paired-run protocol; the shared-node
exception does not carry over to it. Verify correctness before timing and do
not accept results from an unmeasured or unexplained environment.
- Version compatibility covers the locked Rust minimum, CLI and Analysis
product identity, Tool/project prerelease ranges, and beta migration.
- Use Ubuntu 24.04 (glibc 2.39) for the independent archive-only runtime
@@ -114,7 +116,8 @@ The archive is built deterministically from a clean tree at `SOURCE_SHA`:
version="$(cargo metadata --no-deps --format-version 1 --offline \
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
sha="$(git rev-parse HEAD)"
python3 tools/release/package.py --version "$version" --source-sha "$sha"
python3 tools/release/package.py --version "$version" --source-sha "$sha" \
--stdlib-dir stdlib --bundle-pin tools/stdlib/bundle-pin.json
# dist/marqdo-<version>-x86_64-unknown-linux-gnu.tar.gz(+.sha256)
```
@@ -126,9 +129,15 @@ and self-test), `LICENSE-APACHE`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md
artifacts so the examples run without a compiler) and `tests/consumers/`.
`RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`,
`aliases_digest`, `file_count` and `files`. `package.py` recomputes both digests
with the same canonical algorithm as the runtime and refuses to package a mismatch
with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04).
`aliases_digest`, `file_count` and `files`, plus `stdlib.source` (kind,
repository, commit, path) when `--bundle-pin` is given. `--stdlib-dir` is a
required build input and names the unpacked Bundle root; `package.py` verifies
its manifest and recomputes both digests with the same canonical algorithm as
the runtime, and fails on a missing directory, a missing `stdlib.json`, a
tree/alias digest mismatch or a pin mismatch before it stages anything
(ADR-0070, RFC-EXT-0003 H-08 / T-PKG-04). The pin itself is resolved and
verified by `python3 tools/stdlib/bundle.py`; tests, the performance runner and
release CI use the same resolver instead of an implicit checkout path.
The `protocols.analysis` field identifies the default Analysis major.
`protocols.analysis_versions` lists all majors the archive can emit.
The archive smoke exercises a published example and a consumer for each major. The bundled stdlib is a
+18
View File
@@ -53,6 +53,24 @@ Rust harnesses (all in `crates/cli/tests/`):
| `integration_cli.rs` | Real CLI contract: `init`, `check`, `run`, `call`, `inspect`, `fmt`, multi-module imports/cycles, `lock`/`sync --locked`, plugin inspection and explicitly trusted plugin invocation. |
| `execution_events.rs` | Execution Events v1 black-box contract: pure JSONL, seq/terminal ordering, byte-exact base64 chunks, live delivery before exit, value redaction/selection, trace coexistence, truncation, output budget and broken-pipe failure. |
## Stdlib Bundle lanes (ADR-0070)
The product lane consumes one pinned Bundle, never an implicit checkout path:
* `tools/stdlib/bundle-pin.json` pins the Bundle name, version, source commit,
tree digest and alias digest; `tools/stdlib/bundle.py` resolves and verifies
it.
* `crates/cli/tests/support/stdlib.rs` gives the product/conformance harnesses
the same Bundle. `MARQDO_TEST_STDLIB_BUNDLE` or `--stdlib-dir` changes the
location but the Bundle must still match the pin; `MARQDO_TEST_BUNDLE_PIN`
changes the pin file. A bad explicit input fails even when the default
location is valid.
* Loader unit tests in `crates/cli/src/stdlib.rs` build small synthetic
Bundles, so loader logic does not depend on the product tree.
* `tests/independent/language-only.mq.md` is the program
`tools/ci/independent_build.py` runs through a CLI built from a copy without
`stdlib/`; a stdlib-dependent program must fail closed in that copy.
## Running
Use the workspace cargo cache/target as documented in `AGENTS.md`:
+12
View File
@@ -0,0 +1,12 @@
# Language-only program
This fixture uses only the language itself: no `std:` import, no host
capability, no foreign kernel and no plugin. It is the program the
independent-build lane runs through a real CLI built from a copy without the
`stdlib/` tree (ADR-0070).
## @exec main
`值 = 1 + 2`
`return 值`
+217
View File
@@ -0,0 +1,217 @@
#!/usr/bin/env python3
"""Prove the CLI and Provider Worker build without any stdlib source (ADR-0070).
The script exports one committed revision with `git archive`, removes the
`stdlib/` tree (there is no ecosystem checkout either), builds
`marqdo-cli` + `marqdo-provider-worker` with `--locked`, and then:
* runs a language-only program through the freshly built CLI (`check` + `call`);
* requires a stdlib-dependent program to fail closed — the debug source
fallback points at the removed copy, so a success would be a real defect;
* requires no `stdlib/` directory next to the built binary;
* records both binary digests and the source SHA.
Usage:
python3 tools/ci/independent_build.py
python3 tools/ci/independent_build.py --offline --keep
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
BINARIES = ("marqdo", "marqdo-provider-worker")
LANGUAGE_ONLY = Path("tests/independent/language-only.mq.md")
STDLIB_DEPENDENT = Path("examples/hello.mq.md")
MISSING_BUNDLE_PATTERN = re.compile(r"stdlib|symbol\.unknown|打印|print", re.IGNORECASE)
class BuildError(Exception):
pass
def run(
command: list[str],
cwd: Path,
*,
env: dict[str, str] | None = None,
timeout: float = 1800,
check: bool = True,
) -> subprocess.CompletedProcess:
completed = subprocess.run(
command,
cwd=cwd,
env=env,
text=True,
capture_output=True,
timeout=timeout,
)
if check and completed.returncode != 0:
raise BuildError(
f"command failed ({completed.returncode}): {' '.join(command)}\n"
f"stdout:\n{completed.stdout}\nstderr:\n{completed.stderr}"
)
return completed
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def git_output(repo: Path, *arguments: str) -> bytes:
completed = subprocess.run(
["git", "-C", str(repo), *arguments],
capture_output=True,
)
if completed.returncode != 0:
raise BuildError(
f"git {' '.join(arguments)} failed: {completed.stderr.decode(errors='replace')}"
)
return completed.stdout
def export_revision(repo: Path, revision: str, destination: Path) -> str:
try:
head = git_output(repo, "rev-parse", revision).decode().strip()
archive = git_output(repo, "archive", "--format=tar", revision)
except (OSError, subprocess.TimeoutExpired) as error:
raise BuildError(f"cannot export {revision} from {repo}: {error}") from error
destination.mkdir(parents=True, exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:") as tar:
try:
tar.extractall(destination, filter="fully_trusted")
except TypeError: # Python < 3.12 without the PEP 706 backport
tar.extractall(destination)
return head
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", default=str(ROOT))
parser.add_argument("--source", default="HEAD", help="committed revision to export")
parser.add_argument("--work-dir", default=None, help="explicit work directory (kept)")
parser.add_argument("--target-dir", default=None, help="cargo target directory (kept)")
parser.add_argument("--offline", action="store_true")
parser.add_argument("--keep", action="store_true")
parser.add_argument("--timeout", type=float, default=1800.0)
args = parser.parse_args(argv)
repo = Path(args.repo).resolve()
if args.work_dir:
work = Path(args.work_dir).resolve()
if work.exists():
shutil.rmtree(work)
keep = True
else:
work = Path(tempfile.mkdtemp(prefix="marqdo-independent-build-"))
keep = args.keep
target = Path(args.target_dir).resolve() if args.target_dir else work / "target"
source = work / "source"
try:
source_sha = export_revision(repo, args.source, source)
stdlib = source / "stdlib"
if not stdlib.is_dir():
raise BuildError(
"the exported revision has no stdlib/ tree; the lane must remove a "
"real Bundle to prove the build does not need it"
)
shutil.rmtree(stdlib)
if stdlib.exists():
raise BuildError(f"failed to remove {stdlib}")
env = os.environ.copy()
env.pop("MARQDO_STDLIB_DIR", None)
env["CARGO_TARGET_DIR"] = str(target)
env.setdefault("NO_COLOR", "1")
command = ["cargo", "build", "--locked", "-p", "marqdo-cli", "-p", "marqdo-provider-worker"]
if args.offline:
command.append("--offline")
run(command, source, env=env, timeout=args.timeout)
binary = target / "debug" / "marqdo"
if not binary.is_file():
raise BuildError(f"the build produced no CLI binary at {binary}")
if (binary.parent / "stdlib").exists():
raise BuildError(f"a stdlib/ directory appeared next to {binary}")
binaries = {}
for name in BINARIES:
path = target / "debug" / name
if not path.is_file():
raise BuildError(f"the build produced no {name} binary at {path}")
binaries[name] = {"sha256": sha256_file(path), "size": path.stat().st_size}
checked = run([str(binary), "check", str(LANGUAGE_ONLY)], source, env=env, timeout=args.timeout)
called = run(
[str(binary), "call", str(LANGUAGE_ONLY), "main"],
source,
env=env,
timeout=args.timeout,
)
if called.stdout.strip() != "3":
raise BuildError(
f"language-only call printed {called.stdout.strip()!r}, expected '3'"
)
missing = run(
[str(binary), "run", str(STDLIB_DEPENDENT)],
source,
env=env,
timeout=args.timeout,
check=False,
)
if missing.returncode == 0:
raise BuildError(
"a stdlib-dependent program succeeded without any stdlib Bundle "
"(a source fallback exists); this is a release blocker"
)
if not MISSING_BUNDLE_PATTERN.search(missing.stderr + missing.stdout):
raise BuildError(
"the missing-Bundle failure does not name the stdlib/print/symbol "
f"cause:\n{missing.stderr}"
)
summary = {
"schema": "marqdo.independent-build",
"schema_version": 1,
"source_sha": source_sha,
"source_revision": args.source,
"copy": str(source),
"target_dir": str(target),
"binaries": binaries,
"checks": {
"stdlib_source_removed": True,
"language_only_check": "PASS",
"language_only_call": "PASS:3",
"stdlib_dependent_missing_bundle": "PASS",
"no_sibling_stdlib": True,
},
"status": "PASS",
}
print(json.dumps(summary, indent=2, sort_keys=True))
return 0
except BuildError as error:
print(f"independent-build: error: {error}", file=sys.stderr)
return 1
finally:
if not keep:
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
+54 -8
View File
@@ -2,8 +2,8 @@
These tests are stdlib-only and do not build an archive; they pin the digest
helpers that package.py/smoke.py share with the runtime and check that the
release pipeline references a verified stdlib bundle instead of relying on the
compile-time source path.
release pipeline takes the stdlib Bundle as one explicit, verified input
instead of relying on the compile-time source path (ADR-0070).
"""
from __future__ import annotations
@@ -12,6 +12,8 @@ import contextlib
import importlib.util
import io
import json
import shutil
import tempfile
import unittest
from pathlib import Path
@@ -31,10 +33,11 @@ class ReleaseArchiveContractTest(unittest.TestCase):
self.package = load_module("release_package", ROOT / "tools/release/package.py")
self.smoke = load_module("release_smoke", ROOT / "tools/release/smoke.py")
self.manifest = json.loads((ROOT / "stdlib/stdlib.json").read_text(encoding="utf-8"))
self.pin = json.loads((ROOT / "tools/stdlib/bundle-pin.json").read_text(encoding="utf-8"))
def test_tree_digest_matches_manifest(self) -> None:
self.assertEqual(
self.package.stdlib_tree_digest(), self.manifest["digest"]
self.package.stdlib_tree_digest(ROOT / "stdlib"), self.manifest["digest"]
)
self.assertEqual(
self.smoke.stdlib_tree_digest(ROOT / "stdlib"), self.manifest["digest"]
@@ -51,7 +54,9 @@ class ReleaseArchiveContractTest(unittest.TestCase):
)
def test_verify_record_names_required_files_and_count(self) -> None:
record = self.package.verify_stdlib()
record = self.package.verify_stdlib(
ROOT / "stdlib", ROOT / "tools/stdlib/bundle-pin.json"
)
self.assertEqual(record["name"], self.manifest["name"])
self.assertEqual(record["version"], self.manifest["version"])
self.assertEqual(record["tree_digest"], self.manifest["digest"])
@@ -60,13 +65,53 @@ class ReleaseArchiveContractTest(unittest.TestCase):
self.assertIn("io.mq.md", record["files"])
self.assertIn("io/console.mq.md", record["files"])
self.assertEqual(record["file_count"], len(record["files"]))
self.assertEqual(record["source"]["commit"], self.pin["source"]["commit"])
self.assertEqual(record["source"]["kind"], "in-repo")
def test_package_stages_stdlib_next_to_the_binary_and_math_backend(self) -> None:
def test_verify_record_has_no_source_without_a_pin(self) -> None:
record = self.package.verify_stdlib(ROOT / "stdlib")
self.assertNotIn("source", record)
def test_missing_explicit_input_fails_closed(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
with self.assertRaises(SystemExit) as raised:
self.package.verify_stdlib(Path(tmp) / "missing")
self.assertEqual(raised.exception.code, 1)
self.assertIn("does not exist", stderr.getvalue())
def test_tampered_explicit_input_and_wrong_pin_fail_closed(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
copy = Path(tmp) / "stdlib"
shutil.copytree(ROOT / "stdlib", copy)
(copy / "io.mq.md").write_text("## @knowledge tampered\n", encoding="utf-8")
with contextlib.redirect_stderr(io.StringIO()):
with self.assertRaises(SystemExit) as raised:
self.package.verify_stdlib(copy)
self.assertEqual(raised.exception.code, 1)
shutil.rmtree(copy)
shutil.copytree(ROOT / "stdlib", copy)
restamped = json.loads((copy / "stdlib.json").read_text(encoding="utf-8"))
restamped["version"] = "9.9.9"
(copy / "stdlib.json").write_text(json.dumps(restamped), encoding="utf-8")
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
with self.assertRaises(SystemExit) as raised:
self.package.verify_stdlib(copy, ROOT / "tools/stdlib/bundle-pin.json")
self.assertEqual(raised.exception.code, 1)
self.assertIn("does not match the pin", stderr.getvalue())
def test_package_takes_one_explicit_stdlib_dir(self) -> None:
source = (ROOT / "tools/release/package.py").read_text(encoding="utf-8")
self.assertIn('copy_tree(STDLIB, stage_dir / "stdlib")', source)
self.assertIn('"math-backend"', source.replace("math_backend", "math-backend"))
self.assertIn('add_argument("--stdlib-dir", required=True)', source)
self.assertIn('add_argument("--bundle-pin"', source)
self.assertIn('copy_tree(stdlib_dir, stage_dir / "stdlib")', source)
self.assertIn('"stdlib": stdlib_info', source)
self.assertIn("verify_stdlib()", source)
self.assertIn("verify_stdlib(", source)
self.assertNotIn('STDLIB = ROOT / "stdlib"', source)
self.assertIn('"math-backend"', source.replace("math_backend", "math-backend"))
def test_archive_declares_only_current_analysis_revision(self) -> None:
self.smoke.verify_analysis_metadata({"analysis": 3})
@@ -89,6 +134,7 @@ class ReleaseArchiveContractTest(unittest.TestCase):
self.assertIn("verify_stdlib_bundle(install, info)", source)
self.assertIn("verify_stdlib_bundle", source)
self.assertIn("stdlib.hidden", source)
self.assertIn("language-only program runs without the bundled stdlib", source)
self.assertIn("expected 6", source)
self.assertIn("permission.denied", source)
+316
View File
@@ -0,0 +1,316 @@
"""Explicit stdlib Bundle input tests (ADR-0070 / issue #11 Phase A).
Covers the shared resolver (`tools/stdlib/bundle.py`) and the deterministic
package entry point (`tools/pack-stdlib.py`). The digest helpers here are
independent re-implementations so a bug in the shared helper cannot make the
test agree with itself.
"""
from __future__ import annotations
import contextlib
import hashlib
import importlib.util
import io
import json
import os
import tarfile
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def load_module(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
return module
def independent_tree_digest(root: Path) -> str:
digest = hashlib.sha256()
paths = sorted(
(path.relative_to(root).as_posix(), path)
for path in root.rglob("*.mq.md")
if path.is_file()
)
for relative, path in paths:
digest.update(relative.encode())
digest.update(b"\0")
digest.update(path.read_bytes())
digest.update(b"\0")
return "sha256:" + digest.hexdigest()
def independent_aliases_digest(aliases: list[dict]) -> str:
digest = hashlib.sha256()
for alias in sorted(aliases, key=lambda item: (item["target_module"], item["target_function"])):
digest.update(alias["target_module"].encode())
digest.update(b"\0")
digest.update(alias["target_function"].encode())
digest.update(b"\0")
for name in sorted(alias["public_names"]):
digest.update(name.encode())
digest.update(b"\0")
return "sha256:" + digest.hexdigest()
ALIASES = [
{
"public_names": ["print", "打印"],
"target_module": "io.mq.md",
"target_function": "写值",
"expected_signature": "params(值)",
"effects": ["write"],
}
]
def make_bundle(root: Path, *, version: str = "9.9.9", name: str = "marqdo-stdlib") -> dict:
"""Create a minimal Bundle with independently computed digests."""
root.mkdir(parents=True)
(root / "README.md").write_text("# test bundle\n")
(root / "io.mq.md").write_text("## @knowledge io\n")
(root / "io").mkdir()
(root / "io" / "console.mq.md").write_text("## @knowledge console\n")
manifest = {
"schema": "marqdo.stdlib-bundle",
"schema_version": 1,
"name": name,
"version": version,
"digest": independent_tree_digest(root),
"aliases_digest": independent_aliases_digest(ALIASES),
"public_aliases": ALIASES,
}
(root / "stdlib.json").write_text(json.dumps(manifest, indent=2) + "\n")
return manifest
def write_pin(path: Path, manifest: dict, source_path: str, commit: str = "a" * 40) -> dict:
pin = {
"schema": "marqdo.stdlib-bundle-pin",
"schema_version": 1,
"name": manifest["name"],
"version": manifest["version"],
"source": {"kind": "test", "repository": "test/test", "commit": commit, "path": source_path},
"tree_digest": manifest["digest"],
"aliases_digest": manifest["aliases_digest"],
}
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(pin, indent=2) + "\n")
return pin
class BundleResolverTest(unittest.TestCase):
def setUp(self) -> None:
self.bundle = load_module("stdlib_bundle", ROOT / "tools/stdlib/bundle.py")
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.dir = Path(self.tmp.name)
def test_repository_bundle_matches_the_pin(self) -> None:
root, record, pin = self.bundle.resolve()
self.assertEqual(root, (ROOT / "stdlib").resolve())
self.assertEqual(record["tree_digest"], pin["tree_digest"])
self.assertEqual(record["aliases_digest"], pin["aliases_digest"])
self.assertEqual(record["name"], "marqdo-stdlib")
self.assertIn("io.mq.md", record["files"])
def test_explicit_valid_bundle_still_has_to_match_the_pin(self) -> None:
other = self.dir / "other-bundle"
matching = make_bundle(other)
pin_path = self.dir / "pin.json"
write_pin(pin_path, matching, str(other))
root, record, _ = self.bundle.resolve(other, pin_path)
self.assertEqual(root, other.resolve())
self.assertEqual(record["name"], "marqdo-stdlib")
pinned = load_module("stdlib_bundle_pin_check", ROOT / "tools/stdlib/bundle.py")
self.assertRaisesRegex(
pinned.BundleError,
"does not match the pin",
pinned.verify_pin,
{"name": "marqdo-stdlib", "version": "0.1.0",
"tree_digest": "sha256:" + "0" * 64, "aliases_digest": "sha256:" + "0" * 64},
pinned.load_pin(ROOT / "tools/stdlib/bundle-pin.json"),
)
def test_bad_explicit_input_fails_even_when_the_default_is_valid(self) -> None:
with self.assertRaisesRegex(self.bundle.BundleError, "does not exist"):
self.bundle.resolve(self.dir / "missing")
def test_missing_manifest_fails(self) -> None:
bare = self.dir / "bare"
bare.mkdir()
(bare / "io.mq.md").write_text("## @knowledge io\n")
with self.assertRaisesRegex(self.bundle.BundleError, "has no manifest"):
self.bundle.verify(bare)
def test_tree_digest_mismatch_fails(self) -> None:
bundle = self.dir / "tampered"
make_bundle(bundle)
(bundle / "io.mq.md").write_text("## @knowledge tampered\n")
with self.assertRaisesRegex(self.bundle.BundleError, "tree digest mismatch"):
self.bundle.verify(bundle)
def test_alias_digest_mismatch_fails(self) -> None:
bundle = self.dir / "alias-tampered"
manifest = make_bundle(bundle)
manifest["aliases_digest"] = "sha256:" + "0" * 64
(bundle / "stdlib.json").write_text(json.dumps(manifest) + "\n")
with self.assertRaisesRegex(self.bundle.BundleError, "alias digest mismatch"):
self.bundle.verify(bundle)
def test_public_aliases_without_a_digest_fail(self) -> None:
bundle = self.dir / "no-alias-digest"
manifest = make_bundle(bundle)
del manifest["aliases_digest"]
(bundle / "stdlib.json").write_text(json.dumps(manifest) + "\n")
with self.assertRaisesRegex(self.bundle.BundleError, "without aliases_digest"):
self.bundle.verify(bundle)
def test_symlink_inside_the_bundle_is_rejected(self) -> None:
bundle = self.dir / "linked"
make_bundle(bundle)
try:
(bundle / "escape.mq.md").symlink_to("/etc/hostname")
except (OSError, NotImplementedError):
self.skipTest("symbolic links are unavailable on this host")
with self.assertRaisesRegex(self.bundle.BundleError, "symbolic link"):
self.bundle.verify(bundle)
def test_bad_pin_schema_is_rejected(self) -> None:
pin_path = self.dir / "bad-pin.json"
pin_path.write_text(json.dumps({"schema": "other", "schema_version": 1}) + "\n")
with self.assertRaisesRegex(self.bundle.BundleError, "schema_version"):
self.bundle.load_pin(pin_path)
def test_cli_prints_the_resolved_path(self) -> None:
stdout = io.StringIO()
with contextlib.redirect_stdout(stdout):
self.assertEqual(self.bundle.main(["--print-path"]), 0)
self.assertEqual(Path(stdout.getvalue().strip()), (ROOT / "stdlib").resolve())
def test_cli_fails_for_an_invalid_explicit_input(self) -> None:
stderr = io.StringIO()
with contextlib.redirect_stderr(stderr):
self.assertEqual(self.bundle.main(["--stdlib-dir", str(self.dir / "missing")]), 1)
self.assertIn("does not exist", stderr.getvalue())
class PackStdlibTest(unittest.TestCase):
def setUp(self) -> None:
self.pack = load_module("pack_stdlib", ROOT / "tools/pack-stdlib.py")
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.dir = Path(self.tmp.name)
def run_pack(self, *args: str) -> int:
stdout = io.StringIO()
with contextlib.redirect_stdout(stdout):
return self.pack.main(list(args))
def test_stdlib_dir_is_required(self) -> None:
with self.assertRaises(SystemExit) as raised, contextlib.redirect_stderr(io.StringIO()):
self.pack.main([])
self.assertEqual(raised.exception.code, 2)
def test_missing_input_fails(self) -> None:
with self.assertRaises(SystemExit) as raised:
self.run_pack("--stdlib-dir", str(self.dir / "missing"), "--out-dir", str(self.dir))
self.assertIn("does not exist", str(raised.exception.code))
def test_missing_manifest_fails(self) -> None:
bare = self.dir / "bare"
bare.mkdir()
with self.assertRaises(SystemExit) as raised:
self.run_pack("--stdlib-dir", str(bare), "--out-dir", str(self.dir))
self.assertIn("has no manifest", str(raised.exception.code))
def test_tampered_tree_fails(self) -> None:
bundle = self.dir / "bundle"
make_bundle(bundle)
(bundle / "io.mq.md").write_text("## @knowledge tampered\n")
with self.assertRaises(SystemExit) as raised:
self.run_pack("--stdlib-dir", str(bundle), "--out-dir", str(self.dir))
self.assertIn("tree digest mismatch", str(raised.exception.code))
def test_pin_mismatch_fails(self) -> None:
bundle = self.dir / "bundle"
manifest = make_bundle(bundle)
pin_path = self.dir / "pin.json"
pin = write_pin(pin_path, manifest, str(bundle))
pin["tree_digest"] = "sha256:" + "0" * 64
pin_path.write_text(json.dumps(pin) + "\n")
with self.assertRaises(SystemExit) as raised:
self.run_pack(
"--stdlib-dir", str(bundle), "--out-dir", str(self.dir), "--bundle-pin", str(pin_path)
)
self.assertIn("does not match the pin", str(raised.exception.code))
def test_pack_is_deterministic_and_records_the_bundle_identity(self) -> None:
bundle = self.dir / "bundle"
manifest = make_bundle(bundle)
pin_path = self.dir / "pin.json"
write_pin(pin_path, manifest, str(bundle))
first = self.dir / "first"
second = self.dir / "second"
for out in (first, second):
self.assertEqual(
self.run_pack(
"--stdlib-dir", str(bundle), "--out-dir", str(out),
"--bundle-pin", str(pin_path),
),
0,
)
archive_name = "marqdo-stdlib-9.9.9.tar.gz"
first_bytes = (first / archive_name).read_bytes()
self.assertEqual(first_bytes, (second / archive_name).read_bytes())
self.assertEqual(
(first / f"{archive_name}.sha256").read_bytes(),
(second / f"{archive_name}.sha256").read_bytes(),
)
descriptor = json.loads((first / "marqdo-stdlib-9.9.9.json").read_text())
self.assertEqual(descriptor["schema"], "marqdo.stdlib-package")
self.assertEqual(descriptor["schema_version"], 1)
self.assertEqual(descriptor["name"], manifest["name"])
self.assertEqual(descriptor["version"], manifest["version"])
self.assertEqual(descriptor["tree_digest"], independent_tree_digest(bundle))
self.assertEqual(descriptor["aliases_digest"], independent_aliases_digest(ALIASES))
self.assertEqual(
descriptor["archive_sha256"], "sha256:" + hashlib.sha256(first_bytes).hexdigest()
)
self.assertEqual(descriptor["files"], sorted(descriptor["files"]))
with tarfile.open(first / archive_name, mode="r:gz") as archive:
members = archive.getmembers()
self.assertEqual([m.name for m in members], descriptor["files"])
for member in members:
self.assertEqual(member.mtime, 0)
self.assertIn(member.uid, (0,))
self.assertEqual(member.gid, 0)
self.assertEqual(member.mode, 0o644)
self.assertEqual(
archive.extractfile("io.mq.md").read(), (bundle / "io.mq.md").read_bytes()
)
def test_repository_bundle_packs_against_the_committed_pin(self) -> None:
out = self.dir / "out"
self.assertEqual(
self.run_pack(
"--stdlib-dir", str(ROOT / "stdlib"), "--out-dir", str(out),
"--bundle-pin", str(ROOT / "tools/stdlib/bundle-pin.json"),
),
0,
)
descriptor = json.loads((out / "marqdo-stdlib-0.1.0.json").read_text())
manifest = json.loads((ROOT / "stdlib/stdlib.json").read_text())
self.assertEqual(descriptor["tree_digest"], manifest["digest"])
self.assertEqual(descriptor["aliases_digest"], manifest["aliases_digest"])
if __name__ == "__main__":
unittest.main()
+61 -64
View File
@@ -1,74 +1,79 @@
#!/usr/bin/env python3
"""Build a deterministic offline marqdo-stdlib package.
"""Build a deterministic offline marqdo-stdlib package from an explicit Bundle.
The archive is intended for the separate external stdlib repository/release
workflow, not for the CLI's in-repo development fallback. It contains the
Markdown stdlib tree, stdlib.json and README.md, with stable mtimes/ownership.
The input is one unpacked Bundle root (a directory that contains
`stdlib.json`), passed with the required `--stdlib-dir`. This script does not
read the checkout's `stdlib/` implicitly: the CLI release and the separate
stdlib release workflow both name the Bundle they package (ADR-0070).
The archive contains the Markdown stdlib tree, `stdlib.json` and every other
file in the Bundle, with stable mtimes/ownership. An optional `--bundle-pin`
also requires the input to match the pinned name/version/commit/digests.
Usage:
python3 tools/pack-stdlib.py --stdlib-dir stdlib \
--bundle-pin tools/stdlib/bundle-pin.json
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import os
import sys
import tarfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
STDLIB = ROOT / "stdlib"
DIST = ROOT / "dist"
def aliases_digest(manifest: dict) -> str:
digest = hashlib.sha256()
for alias in sorted(
manifest.get("public_aliases", []),
key=lambda a: (a["target_module"], a["target_function"]),
):
digest.update(alias["target_module"].encode())
digest.update(b"\0")
digest.update(alias["target_function"].encode())
digest.update(b"\0")
for name in sorted(alias["public_names"]):
digest.update(name.encode())
digest.update(b"\0")
return f"sha256:{digest.hexdigest()}"
sys.path.insert(0, str(Path(__file__).resolve().parent / "stdlib"))
import bundle as stdlib_bundle # noqa: E402
def tree_digest() -> str:
digest = hashlib.sha256()
for path in sorted(
STDLIB.rglob("*.mq.md"), key=lambda p: p.relative_to(STDLIB).as_posix()
):
relative = path.relative_to(STDLIB).as_posix()
digest.update(relative.encode())
digest.update(b"\0")
digest.update(path.read_bytes())
digest.update(b"\0")
return digest.hexdigest()
def gzip_open(raw):
import gzip
return gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, filename="")
def main() -> int:
manifest = json.loads((STDLIB / "stdlib.json").read_text())
version = manifest["version"]
digest = tree_digest()
if manifest["digest"] != f"sha256:{digest}":
raise SystemExit("stdlib.json digest does not match the tree")
alias_digest = aliases_digest(manifest)
if manifest.get("aliases_digest") != alias_digest:
raise SystemExit("stdlib.json aliases_digest does not match public_aliases")
def verify_input(root: Path, pin_path: Path | None) -> dict:
try:
record = stdlib_bundle.verify(root)
stdlib_bundle.require_files(record, ("stdlib.json",))
if record["aliases_digest"] is None:
raise stdlib_bundle.BundleError(
f"{root / 'stdlib.json'} declares no aliases_digest"
)
if pin_path is not None:
pin = stdlib_bundle.load_pin(pin_path)
stdlib_bundle.verify_pin(record, pin)
except stdlib_bundle.BundleError as error:
raise SystemExit(f"pack-stdlib: error: {error}") from error
return record
files = sorted(
[p for p in STDLIB.rglob("*") if p.is_file() and p.name != "stdlib.json"]
+ [STDLIB / "stdlib.json"],
key=lambda p: p.relative_to(STDLIB).as_posix(),
)
DIST.mkdir(exist_ok=True)
archive = DIST / f"marqdo-stdlib-{version}.tar.gz"
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--stdlib-dir", required=True)
parser.add_argument("--out-dir", default=str(DIST))
parser.add_argument("--bundle-pin", default=None)
args = parser.parse_args(argv)
root = Path(args.stdlib_dir)
record = verify_input(root, Path(args.bundle_pin) if args.bundle_pin else None)
version = record["version"]
files = [root / name for name in record["files"]]
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
archive = out_dir / f"marqdo-stdlib-{version}.tar.gz"
with archive.open("wb") as raw:
with gzip_open(raw) as gz:
with tarfile.open(fileobj=gz, mode="w") as tar:
for path in files:
relative = path.relative_to(STDLIB).as_posix()
relative = path.relative_to(root).as_posix()
info = tarfile.TarInfo(name=relative)
data = path.read_bytes()
info.size = len(data)
@@ -81,28 +86,20 @@ def main() -> int:
descriptor = {
"schema": "marqdo.stdlib-package",
"schema_version": 1,
"name": manifest["name"],
"name": record["name"],
"version": version,
"tree_digest": f"sha256:{digest}",
"aliases_digest": alias_digest,
"tree_digest": record["tree_digest"],
"aliases_digest": record["aliases_digest"],
"archive": archive.name,
"archive_sha256": f"sha256:{archive_sha}",
"files": [p.relative_to(STDLIB).as_posix() for p in files],
"files": record["files"],
}
descriptor_path = DIST / f"marqdo-stdlib-{version}.json"
descriptor_path = out_dir / f"marqdo-stdlib-{version}.json"
descriptor_path.write_text(json.dumps(descriptor, indent=2) + "\n")
(DIST / f"{archive.name}.sha256").write_text(
f"{archive_sha} {archive.name}\n"
)
(out_dir / f"{archive.name}.sha256").write_text(f"{archive_sha} {archive.name}\n")
print(json.dumps(descriptor, indent=2))
return 0
def gzip_open(raw):
import gzip
return gzip.GzipFile(fileobj=raw, mode="wb", mtime=0, filename="")
if __name__ == "__main__":
raise SystemExit(main())
raise SystemExit(main(sys.argv[1:]))
+5
View File
@@ -27,6 +27,11 @@ workload whose wire output did not match the committed expected digest.
governor, CPU affinity and toolchain. For an approved-node comparison
it also requires an approved, correctness-verified MEASURED baseline.
Record competing load and investigate differences before sign-off.
* One explicit Bundle: `--stdlib-dir` (default: the pinned Bundle) is verified
against `tools/stdlib/bundle-pin.json`, and every workload receives it as
`MARQDO_STDLIB_DIR`. The report records the Bundle name, version, tree/alias
digests and source commit. A bad input or digest mismatch fails before any
workload runs; there is no checkout fallback (ADR-0070).
* Avoid TCG/QEMU for final performance numbers; use native or KVM with fixed
CPU affinity (`--cpu-list`) and an administrator-approved governor.
* The suggested investigation thresholds are p50 +15% and peak RSS +20%; they
+25 -2
View File
@@ -38,6 +38,9 @@ EXPECTED = ROOT / "tools" / "perf" / "expected"
SCHEMA = "marqdo.perf.v2"
MIN_WARMUPS = 5
MIN_SAMPLES = 20
sys.path.insert(0, str(ROOT / "tools" / "stdlib"))
import bundle as stdlib_bundle # noqa: E402
P50_REGRESSION = 0.15
RSS_REGRESSION = 0.20
@@ -312,6 +315,7 @@ def run_workload(
record: bool,
timeout: float,
cpu_list: str,
stdlib_dir: Path,
) -> dict:
name = workload["name"]
prefix = []
@@ -325,8 +329,9 @@ def run_workload(
measured_argv = prefix + [str(binary)] + (workload.get("measure_argv") or workload["argv"])
env = dict(os.environ)
env.pop("MARQDO_STDLIB_DIR", None)
if not (binary.parent / "stdlib" / "stdlib.json").is_file():
env["MARQDO_STDLIB_DIR"] = str(ROOT / "stdlib")
# One explicit, pinned Bundle for every workload; no sibling or checkout
# fallback (ADR-0070).
env["MARQDO_STDLIB_DIR"] = str(stdlib_dir)
env.setdefault("NO_COLOR", "1")
expected_document = load_expected(name)
expected = expected_document.get("wire_sha256") if expected_document else None
@@ -514,6 +519,8 @@ def compare_baseline(report: dict, baseline: dict) -> list[dict]:
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", default=str(ROOT / "target" / "release" / "marqdo"))
parser.add_argument("--stdlib-dir", default=None)
parser.add_argument("--bundle-pin", default=str(ROOT / "tools" / "stdlib" / "bundle-pin.json"))
parser.add_argument("--no-build", action="store_true")
parser.add_argument("--warmups", type=int, default=MIN_WARMUPS)
parser.add_argument("--samples", type=int, default=MIN_SAMPLES)
@@ -528,6 +535,13 @@ def main(argv: list[str]) -> int:
parser.add_argument("--allow-smoke", action="store_true")
args = parser.parse_args(argv)
try:
stdlib_dir, stdlib_record, stdlib_pin = stdlib_bundle.resolve(
args.stdlib_dir, Path(args.bundle_pin)
)
except stdlib_bundle.BundleError as error:
raise SystemExit(f"perf: error: {error}") from error
if args.samples < 1 or args.warmups < 0:
raise SystemExit("samples must be >= 1 and warmups >= 0")
if (args.samples < MIN_SAMPLES or args.warmups < MIN_WARMUPS) and not args.allow_smoke:
@@ -571,6 +585,7 @@ def main(argv: list[str]) -> int:
args.record_expected,
args.timeout,
args.cpu_list,
stdlib_dir,
)
results.append(result)
print(
@@ -589,6 +604,14 @@ def main(argv: list[str]) -> int:
report = {
"schema": SCHEMA,
"source_sha": source_sha,
"stdlib": {
"name": stdlib_record["name"],
"version": stdlib_record["version"],
"tree_digest": stdlib_record["tree_digest"],
"aliases_digest": stdlib_record["aliases_digest"],
"source_commit": stdlib_pin["source"].get("commit"),
"root": str(stdlib_dir),
},
"platform_id": args.platform_id,
"environment_approved": bool(args.approved_node),
"binary": {
+1
View File
@@ -51,4 +51,5 @@ docker run --rm --network none --user 65534:65534 \
exit 1
fi
grep -E "stdlib|symbol\.unknown|打印" /tmp/missing-stdlib.log
test "$(./marqdo call examples/factorial.mq.md 阶乘 --arg n=5)" = 120
' sh "$version" "$source_sha"
+68 -75
View File
@@ -4,7 +4,13 @@
The archive is deterministic (sorted entries, commit timestamp, uid/gid 0) and
contains the CLI, the provider worker helper (same directory, same target), the
licenses/changelog/compatibility matrix, the public specs, the developer docs,
the runnable examples and the public protocol consumers.
the runnable examples, the public protocol consumers and the stdlib Bundle that
`--stdlib-dir` names.
The stdlib Bundle is one required, explicit build input (ADR-0070): a missing
directory, missing manifest, tree/alias digest mismatch or pin mismatch fails
before anything is staged. An optional `--bundle-pin` also records the pinned
source commit in `RELEASE_INFO.json.stdlib.source`.
It refuses to package a dirty tree, a version that does not match the Cargo
workspace, or a HEAD that differs from `--source-sha`, and it fails if the
@@ -16,7 +22,9 @@ Usage (from the repository root, after
python3 tools/release/package.py \
--source-sha "$(git rev-parse HEAD)" \
--version 3.0.0-rc.4
--version 3.0.0-rc.4 \
--stdlib-dir stdlib \
--bundle-pin tools/stdlib/bundle-pin.json
"""
from __future__ import annotations
@@ -34,7 +42,7 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
BINARIES = ("marqdo", "marqdo-provider-worker")
STDLIB = ROOT / "stdlib"
PRODUCT_STDLIB_FILES = ("stdlib.json", "io.mq.md", "io/console.mq.md")
EXAMPLES_WITH_BUILD = (
"plugin-demo",
"plugin-multi-export",
@@ -42,6 +50,9 @@ EXAMPLES_WITH_BUILD = (
"math-backend",
)
sys.path.insert(0, str(ROOT / "tools" / "stdlib"))
import bundle as stdlib_bundle # noqa: E402
def fail(message: str) -> "NoReturn":
print(f"package: error: {message}", file=sys.stderr)
@@ -64,81 +75,51 @@ def sha256_file(path: Path) -> str:
return digest.hexdigest()
def sha256_bytes(*chunks: bytes) -> str:
digest = hashlib.sha256()
for chunk in chunks:
digest.update(chunk)
return "sha256:" + digest.hexdigest()
def stdlib_tree_digest(root: Path) -> str:
"""Canonical stdlib tree digest, byte-identical to the CLI loader.
def stdlib_tree_digest(root: Path = STDLIB) -> str:
"""Canonical stdlib tree digest, byte-identical to
`marqdo_cli::stdlib::tree_digest`: sorted `*.mq.md` relative POSIX paths,
`path + NUL + bytes + NUL`."""
paths = sorted(
(path.relative_to(root).as_posix(), path)
for path in root.rglob("*.mq.md")
if path.is_file()
)
return sha256_bytes(
*(
chunk
for relative, path in paths
for chunk in (relative.encode(), b"\0", path.read_bytes(), b"\0")
)
)
The algorithm lives in `tools/stdlib/bundle.py` (ADR-0070); `root` is the
explicit `--stdlib-dir` input, never an implicit checkout path.
"""
return stdlib_bundle.tree_digest(root)
def stdlib_aliases_digest(manifest: dict) -> str:
"""Canonical public-alias digest, byte-identical to the CLI loader."""
chunks: list[bytes] = []
aliases = sorted(
manifest.get("public_aliases", []),
key=lambda alias: (alias["target_module"], alias["target_function"]),
)
for alias in aliases:
chunks.append(alias["target_module"].encode())
chunks.append(b"\0")
chunks.append(alias["target_function"].encode())
chunks.append(b"\0")
for name in sorted(alias["public_names"]):
chunks.append(name.encode())
chunks.append(b"\0")
return sha256_bytes(*chunks)
return stdlib_bundle.aliases_digest(manifest)
def verify_stdlib() -> dict:
"""Validate the shipped stdlib tree and return the RELEASE_INFO record."""
manifest_path = STDLIB / "stdlib.json"
if not manifest_path.is_file():
fail(f"missing bundled stdlib manifest {manifest_path}")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
tree = stdlib_tree_digest()
aliases = stdlib_aliases_digest(manifest)
if tree != manifest.get("digest"):
fail(f"stdlib tree digest {tree} does not match stdlib.json digest {manifest.get('digest')}")
if aliases != manifest.get("aliases_digest"):
fail(
f"stdlib alias digest {aliases} does not match stdlib.json "
f"aliases_digest {manifest.get('aliases_digest')}"
)
required = ["stdlib.json", "io.mq.md", "io/console.mq.md"]
files = sorted(
path.relative_to(STDLIB).as_posix()
for path in STDLIB.rglob("*")
if path.is_file()
)
for name in required:
if name not in files:
fail(f"bundled stdlib is missing required file {name}")
return {
"name": manifest.get("name"),
"version": manifest.get("version"),
"tree_digest": tree,
"aliases_digest": aliases,
"file_count": len(files),
"files": files,
}
def verify_stdlib(root: Path, pin_path: Path | None = None) -> dict:
"""Validate the explicit Bundle root and return the RELEASE_INFO record."""
root = Path(root)
try:
record = stdlib_bundle.verify(root)
stdlib_bundle.require_files(record, PRODUCT_STDLIB_FILES)
if record["aliases_digest"] is None:
raise stdlib_bundle.BundleError(
f"{root / 'stdlib.json'} declares no aliases_digest"
)
info = {
"name": record["name"],
"version": record["version"],
"tree_digest": record["tree_digest"],
"aliases_digest": record["aliases_digest"],
"file_count": record["file_count"],
"files": record["files"],
}
if pin_path is not None:
pin = stdlib_bundle.load_pin(pin_path)
stdlib_bundle.verify_pin(record, pin)
source = pin["source"]
info["source"] = {
"kind": source.get("kind"),
"repository": source.get("repository"),
"commit": source.get("commit"),
"path": source.get("path"),
}
return info
except stdlib_bundle.BundleError as error:
fail(str(error))
def host_target() -> str:
@@ -206,7 +187,14 @@ def copy_tree(source: Path, destination: Path) -> None:
shutil.copytree(source, destination, dirs_exist_ok=True)
def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
def stage(
stage_dir: Path,
version: str,
source_sha: str,
target: str,
stdlib_dir: Path,
stdlib_info: dict,
) -> dict:
stage_dir.mkdir(parents=True)
release_dir = ROOT / "target" / "release"
for name in BINARIES:
@@ -226,7 +214,7 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
# The bundled stdlib is a required runtime artifact, not a build-machine
# side effect: copy the verified tree next to the binary (ADR/SPEC H-08).
copy_tree(STDLIB, stage_dir / "stdlib")
copy_tree(stdlib_dir, stage_dir / "stdlib")
# Examples without local build output, then the freshly built extension
# artifacts so a clean install can run every example without a compiler.
@@ -242,7 +230,6 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
shutil.copy2(limitations, stage_dir / "KNOWN_LIMITATIONS.md")
commit_time = int(git("show", "-s", "--format=%ct", "HEAD"))
stdlib_info = verify_stdlib()
binaries = {
name: {
"sha256": sha256_file(stage_dir / name),
@@ -326,6 +313,8 @@ def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source-sha", required=True)
parser.add_argument("--version", required=True)
parser.add_argument("--stdlib-dir", required=True)
parser.add_argument("--bundle-pin", default=None)
parser.add_argument("--target", default=None)
parser.add_argument("--out-dir", default=str(ROOT / "dist"))
parser.add_argument("--skip-example-build", action="store_true")
@@ -335,6 +324,10 @@ def main(argv: list[str]) -> int:
ch not in "0123456789abcdef" for ch in args.source_sha
):
fail("--source-sha must be a full lowercase 40-character commit SHA")
stdlib_dir = Path(args.stdlib_dir)
stdlib_info = verify_stdlib(
stdlib_dir, Path(args.bundle_pin) if args.bundle_pin else None
)
check_clean(args.source_sha)
version = workspace_version()
if version != args.version:
@@ -349,7 +342,7 @@ def main(argv: list[str]) -> int:
out_dir.mkdir(parents=True, exist_ok=True)
stage_dir = out_dir / f"marqdo-{version}-{target}"
shutil.rmtree(stage_dir, ignore_errors=True)
staged = stage(stage_dir, version, args.source_sha, target)
staged = stage(stage_dir, version, args.source_sha, target, stdlib_dir, stdlib_info)
archive = out_dir / f"marqdo-{version}-{target}.tar.gz"
archive.unlink(missing_ok=True)
make_archive(stage_dir, archive, staged["commit_time"])
+10
View File
@@ -281,6 +281,16 @@ def main(argv: list[str]) -> int:
if "stdlib" not in message and "打印" not in message and "symbol.unknown" not in message:
fail(f"missing-stdlib failure is not explicit: {message!r}")
print("smoke: bundled stdlib missing -> fail-closed OK")
# A program that uses only the language must still run.
language_only = runner.run(
["call", "examples/factorial.mq.md", "阶乘", "--arg", "n=5"]
).stdout.strip()
if language_only != "120":
fail(
f"language-only call failed without the bundled stdlib: "
f"{language_only!r}"
)
print("smoke: language-only program runs without the bundled stdlib")
finally:
hidden.rename(install / "stdlib")
factor = runner.run(
+15
View File
@@ -0,0 +1,15 @@
{
"schema": "marqdo.stdlib-bundle-pin",
"schema_version": 1,
"name": "marqdo-stdlib",
"version": "0.1.0",
"source": {
"kind": "in-repo",
"repository": "cflmy/marqdo-cli",
"commit": "2cbde54602c07f62a62f341400bc9cb4764a93f8",
"path": "stdlib",
"note": "Phase A (ADR-0070): the pinned Bundle is the checkout tree at this commit. Phase B replaces this record with the accepted ecosystem Bundle commit and digest; do not change it in the same commit as test fixtures."
},
"tree_digest": "sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713",
"aliases_digest": "sha256:5f513c0fdbb3c1e9829be3c9fa23a2d1e89cb8510073fb5eb1e8e2f5265a83bb"
}
+308
View File
@@ -0,0 +1,308 @@
#!/usr/bin/env python3
"""One resolver and verifier for a stdlib Bundle (ADR-0070).
Every source-side consumer that needs the official Bundle — packaging tools,
product tests, the performance runner and release CI — resolves it through
this module instead of concatenating a checkout path. The identity comes from
`tools/stdlib/bundle-pin.json` (name, version, source commit, tree digest,
alias digest); an explicit input may change the location but must still match
the pinned digests.
The digest algorithms are byte-identical to `marqdo_cli::stdlib` and to
`tools/release/smoke.py` (which stays an independent verifier of the shipped
archive). Nothing here is used by the running CLI.
Usage:
python3 tools/stdlib/bundle.py [--stdlib-dir PATH] [--pin PATH] [--print-path]
Exit status is 1 for an invalid Bundle and 2 for a bad command line.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
PIN_PATH = ROOT / "tools" / "stdlib" / "bundle-pin.json"
PIN_SCHEMA = "marqdo.stdlib-bundle-pin"
PIN_SCHEMA_VERSION = 1
REQUIRED_MANIFEST_FIELDS = ("name", "version", "digest")
class BundleError(Exception):
"""An input is not a verifiable stdlib Bundle."""
def _sha256_bytes(*chunks: bytes) -> str:
digest = hashlib.sha256()
for chunk in chunks:
digest.update(chunk)
return "sha256:" + digest.hexdigest()
def _walk_files(root: Path) -> list[Path]:
"""Every regular file under `root`, sorted, rejecting symlinks.
Deterministic packaging must not follow a link outside the Bundle root or
archive a link whose target differs by platform.
"""
files: list[Path] = []
for dirpath, dirnames, filenames in os.walk(root, followlinks=False):
dirnames.sort()
base = Path(dirpath)
for name in dirnames:
if (base / name).is_symlink():
raise BundleError(
f"stdlib Bundle contains a symbolic link directory: "
f"{(base / name).relative_to(root).as_posix()}"
)
for name in sorted(filenames):
path = base / name
if path.is_symlink():
raise BundleError(
f"stdlib Bundle contains a symbolic link: "
f"{path.relative_to(root).as_posix()}"
)
if path.is_file():
files.append(path)
files.sort(key=lambda path: path.relative_to(root).as_posix())
return files
def load_manifest(root: Path) -> dict:
manifest_path = root / "stdlib.json"
if not root.is_dir():
raise BundleError(f"stdlib Bundle directory does not exist: {root}")
if not manifest_path.is_file():
raise BundleError(f"stdlib Bundle has no manifest: {manifest_path}")
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
raise BundleError(f"cannot read valid JSON from {manifest_path}: {error}") from error
if not isinstance(manifest, dict):
raise BundleError(f"{manifest_path} must contain a JSON object")
for field in REQUIRED_MANIFEST_FIELDS:
value = manifest.get(field)
if not isinstance(value, str) or not value:
raise BundleError(f"{manifest_path} has no non-empty `{field}`")
return manifest
def tree_digest(root: Path) -> str:
"""`relative POSIX path + NUL + bytes + NUL` over every `*.mq.md` file."""
root = Path(root)
chunks: list[bytes] = []
for path in _walk_files(root):
if not path.name.endswith(".mq.md"):
continue
chunks.append(path.relative_to(root).as_posix().encode())
chunks.append(b"\0")
chunks.append(path.read_bytes())
chunks.append(b"\0")
return _sha256_bytes(*chunks)
def aliases_digest(manifest: dict) -> str:
"""Canonical digest over `public_aliases`, byte-identical to the loader."""
chunks: list[bytes] = []
aliases = sorted(
manifest.get("public_aliases", []),
key=lambda alias: (alias["target_module"], alias["target_function"]),
)
for alias in aliases:
chunks.append(alias["target_module"].encode())
chunks.append(b"\0")
chunks.append(alias["target_function"].encode())
chunks.append(b"\0")
for name in sorted(alias["public_names"]):
chunks.append(name.encode())
chunks.append(b"\0")
return _sha256_bytes(*chunks)
def _verify_aliases(manifest: dict, manifest_path: Path) -> list[dict]:
raw = manifest.get("public_aliases", [])
if not isinstance(raw, list):
raise BundleError(f"{manifest_path} public_aliases must be an array")
seen: set[str] = set()
aliases: list[dict] = []
for entry in raw:
if not isinstance(entry, dict):
raise BundleError(f"{manifest_path} public alias must be an object")
names = entry.get("public_names")
if not isinstance(names, list) or not names:
raise BundleError(f"{manifest_path} public alias declares no names")
for name in names:
if not isinstance(name, str) or not name:
raise BundleError(f"{manifest_path} public alias name must be a non-empty string")
if name in seen:
raise BundleError(f"{manifest_path} public alias name `{name}` is declared twice")
seen.add(name)
module = entry.get("target_module")
if not isinstance(module, str) or not module:
raise BundleError(f"{manifest_path} public alias has no target_module")
relative = Path(module)
if relative.is_absolute() or ".." in relative.parts:
raise BundleError(
f"{manifest_path} public alias target_module `{module}` must stay inside the Bundle"
)
function = entry.get("target_function")
if not isinstance(function, str) or not function:
raise BundleError(f"{manifest_path} public alias has no target_function")
aliases.append(entry)
aliases.sort(key=lambda alias: (alias["target_module"], alias["target_function"]))
return aliases
def verify(root: Path) -> dict:
"""Validate one unpacked Bundle root and return its identity record."""
root = Path(root)
manifest = load_manifest(root)
manifest_path = root / "stdlib.json"
tree = tree_digest(root)
declared_tree = manifest["digest"]
if declared_tree != tree:
raise BundleError(
f"stdlib tree digest mismatch: stdlib.json declares {declared_tree}, "
f"the files are {tree}"
)
aliases = _verify_aliases(manifest, manifest_path)
declared_aliases = manifest.get("aliases_digest")
actual_aliases = aliases_digest(manifest)
if declared_aliases is None and aliases:
raise BundleError(f"{manifest_path} declares public_aliases without aliases_digest")
if declared_aliases is not None and declared_aliases != actual_aliases:
raise BundleError(
f"stdlib public-alias digest mismatch: stdlib.json declares {declared_aliases}, "
f"the alias table is {actual_aliases}"
)
files = sorted(path.relative_to(root).as_posix() for path in _walk_files(root))
modules = [name for name in files if name.endswith(".mq.md")]
if not modules:
raise BundleError(f"stdlib Bundle {root} contains no .mq.md module")
return {
"name": manifest["name"],
"version": manifest["version"],
"tree_digest": tree,
"aliases_digest": actual_aliases if declared_aliases is not None else None,
"file_count": len(files),
"files": files,
}
def require_files(record: dict, required: tuple[str, ...]) -> None:
missing = [name for name in required if name not in record["files"]]
if missing:
raise BundleError(
"stdlib Bundle is missing required file(s): " + ", ".join(missing)
)
def load_pin(path: Path = PIN_PATH) -> dict:
path = Path(path)
try:
pin = json.loads(path.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error:
raise BundleError(f"cannot read Bundle pin {path}: {error}") from error
if not isinstance(pin, dict):
raise BundleError(f"Bundle pin {path} must contain a JSON object")
if pin.get("schema") != PIN_SCHEMA or pin.get("schema_version") != PIN_SCHEMA_VERSION:
raise BundleError(
f"Bundle pin {path} must be {PIN_SCHEMA} schema_version {PIN_SCHEMA_VERSION}"
)
source = pin.get("source")
if not isinstance(source, dict) or not isinstance(source.get("path"), str):
raise BundleError(f"Bundle pin {path} has no source.path")
for field in ("name", "version", "tree_digest", "aliases_digest"):
if not isinstance(pin.get(field), str) or not pin[field]:
raise BundleError(f"Bundle pin {path} has no non-empty `{field}`")
return pin
def verify_pin(record: dict, pin: dict) -> None:
"""Require a verified Bundle record to match the pinned identity."""
for field in ("name", "version", "tree_digest", "aliases_digest"):
if record.get(field) != pin.get(field):
raise BundleError(
f"stdlib Bundle does not match the pin: {field} is "
f"{record.get(field)!r}, the pin records {pin.get(field)!r}"
)
def resolve(
explicit: str | Path | None = None,
pin_path: Path = PIN_PATH,
*,
require_pin: bool = True,
) -> tuple[Path, dict, dict]:
"""Resolve and verify the Bundle, returning `(root, record, pin)`.
`explicit` overrides the pinned location but never the pinned identity
unless `require_pin` is false. A bad explicit input fails even when the
default location is valid; there is no fallback.
"""
pin = load_pin(pin_path)
if explicit is None:
root = ROOT / pin["source"]["path"]
else:
root = Path(explicit)
record = verify(root)
if require_pin:
verify_pin(record, pin)
require_files(
record,
(
"stdlib.json",
"io.mq.md",
"io/console.mq.md",
),
)
return root.resolve(), record, pin
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(
description="Resolve and verify the pinned stdlib Bundle (ADR-0070)."
)
parser.add_argument("--stdlib-dir", default=None)
parser.add_argument("--pin", default=str(PIN_PATH))
parser.add_argument("--print-path", action="store_true")
parser.add_argument("--dump-pin", action="store_true")
args = parser.parse_args(argv)
try:
root, record, pin = resolve(args.stdlib_dir, Path(args.pin))
except BundleError as error:
print(f"bundle: error: {error}", file=sys.stderr)
return 1
if args.print_path:
print(root)
return 0
if args.dump_pin:
print(json.dumps(pin, indent=2, sort_keys=True))
return 0
print(
json.dumps(
{
"root": str(root),
"name": record["name"],
"version": record["version"],
"tree_digest": record["tree_digest"],
"aliases_digest": record["aliases_digest"],
"source_commit": pin["source"].get("commit"),
"file_count": record["file_count"],
},
indent=2,
sort_keys=True,
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))