refactor: accept the ecosystem stdlib Bundle and remove the in-repo sources
ci/woodpecker/push/main Pipeline failed
ci/woodpecker/pr/main Pipeline failed

Phase B of ADR-0070 (issue #11): the CLI no longer owns standard-library
sources. The pin names the accepted ecosystem Bundle (marqdo-stdlib@0.2.0,
root commit + tree/alias digests); tools/ci/fetch_ecosystem_bundle.py
materializes it from the pinned root commit and stdlib gitlinks and verifies
the digests. bundle.py and the test harness require an explicit verified Bundle
for the accepted identity, and runtime discovery has no compile-time source
fallback in any profile.

Delete stdlib/ (modules, self-tests, aliases manifest). Module and domain tests
stay with their component owners; the CLI product lane now verifies the
external Bundle's public surface, std: resolution and official print/打印 alias
routing (tests/product-stdlib). Composition assertions whose owner is the
ecosystem (Table split, print-format equivalence) moved to the root Bundle
acceptance; the generic TCP round-trip stays a CLI test. Spawned-CLI tests name
the verified Bundle explicitly.

CI (Woodpecker + GitHub) materializes the pinned Bundle before product tests,
packaging and performance lanes; packaging and release take --stdlib-dir from
that artifact. Docs, STATUS, ADR-0070 and a Phase B evidence record updated.

Refs cflmy/marqdo#9, cflmy/marqdo-cli#11
This commit is contained in:
cflmy committed 2026-11-27 01:04:01 +08:00
1 parent f8b82d4143
commit 72f57beee0
85 files changed
+796 -5939

No files matched your search

+3 -5
View File
@@ -3,6 +3,8 @@
//! These drive the real CLI binary: exact source/AST/scope projection, explicit
//! reference states, output safety, Observation digest binding, independent
//! consumers and schema/semantic mutation rejection.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
@@ -50,12 +52,8 @@ impl Drop for TempDir {
}
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(binary())
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+3 -5
View File
@@ -1,5 +1,7 @@
//! Public Analysis and Observation black-box contracts (spec/analysis.md,
//! spec/observation.md).
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
@@ -34,12 +36,8 @@ impl Drop for TempDir {
}
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(binary())
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+26 -14
View File
@@ -2,12 +2,12 @@
//!
//! These checks pin the documented layering: the engine depends on the neutral
//! Host contract (never the native host), the plugin ABI contract carries no
//! loader/worker execution side, the bundled stdlib stays in this repository,
//! `std:` import targets resolve only inside the bundle, and the host keeps the
//! loader/worker execution side, the stdlib Bundle is an explicit ecosystem
//! input rather than an in-repo source tree, `std:` import targets resolve only
//! inside the bundle, and the host keeps the
//! documented stdio/file/TCP resource endpoints. They are source and digest
//! checks, not an OS-sandbox proof; `tools/ci/check_dependency_boundaries.py`
//! adds the Cargo-metadata graph gate.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
@@ -140,24 +140,36 @@ fn engine_depends_on_the_neutral_host_contract_only() {
}
#[test]
fn bundled_stdlib_stays_in_this_repository_and_matches_its_digest() {
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"
fn stdlib_sources_live_in_the_ecosystem_not_in_this_repository() {
// Phase B (ADR-0070): the in-repo source tree is gone. The accepted Bundle
// identity is the ecosystem pin; product tests consume an explicit, verified
// Bundle (CI materializes it with tools/ci/fetch_ecosystem_bundle.py).
assert!(
!repo_root().join("stdlib").exists(),
"Phase B must not carry an in-repo stdlib source tree"
);
let pin = stdlib_support::BundlePin::committed();
assert!(
pin.source_path.is_none(),
"the accepted Bundle pin must name the ecosystem source, not a vendored path"
);
assert_eq!(pin.name, "marqdo-stdlib");
assert_eq!(pin.version, "0.2.0");
assert_eq!(pin.source_commit.len(), 40);
let root = stdlib_support::bundle_dir();
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(root.join("stdlib.json")).unwrap()).unwrap();
assert_eq!(manifest["name"], "marqdo-stdlib");
assert_eq!(manifest["version"], "0.1.0");
assert_eq!(manifest["name"], pin.name);
assert_eq!(manifest["version"], pin.version);
let declared = manifest["digest"].as_str().expect("digest string");
assert_eq!(
declared, pin.tree_digest,
"the resolved Bundle must match the pin"
);
let actual = format!("sha256:{}", tree_digest(&root).unwrap());
assert_eq!(
actual, declared,
"stdlib digest mismatch; regenerate it with tools/pack-stdlib.py and commit the digest"
"stdlib digest mismatch; rebuild the Bundle from the pinned ecosystem gitlinks"
);
}
+4 -1
View File
@@ -4,6 +4,9 @@
//! point is to prove that `check` and `run` share one static resolution and
//! that the runtime never guesses a plugin from a dotted string prefix.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
@@ -49,7 +52,7 @@ fn repo() -> PathBuf {
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+2 -2
View File
@@ -18,11 +18,11 @@
//! Developer note: `UPDATE_SEMANTICS_GOLDENS=1` rewrites `value`/`stdout` from
//! the implementation. Never use it without hand-checking every rewritten
//! expectation; the checked-in goldens were reviewed individually.
use std::fs;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::fs;
use std::path::{Path, PathBuf};
use marqdo_host::{Capabilities, StdHost};
+7 -30
View File
@@ -1,11 +1,13 @@
//! R6 integration examples that do not require an official external repo.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::path::Path;
use std::process::{Command, Output};
use std::process::Output;
fn repo() -> &'static Path {
Path::new(env!("CARGO_MANIFEST_DIR"))
@@ -16,7 +18,7 @@ fn repo() -> &'static Path {
}
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(repo())
.output()
@@ -27,31 +29,6 @@ fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
#[test]
fn mqmd_stdlib_print_output_matches_builtin_print() {
let output = cli(&["run", "stdlib/demo.mq.md"]);
assert_eq!(output.status.code(), Some(0), "{}", stderr(&output));
let stdout = String::from_utf8_lossy(&output.stdout);
let lines: Vec<&str> = stdout.lines().collect();
assert_eq!(lines.len(), 6, "{stdout:?}");
for pair in [(0, 1), (2, 3), (4, 5)] {
assert_eq!(
lines[pair.0], lines[pair.1],
"stdlib formatting differs from 打印 at line {}",
pair.0
);
}
assert_eq!(
lines[0],
r#"["文本", 2, 1.5, [3, true], {a: 1, b: "x"}, None]"#
);
assert_eq!(lines[2], "Table[名称 | 分数]{甲 | 87; 乙 | 92}");
assert_eq!(
lines[4],
r#"[Formula("a = 1"), Code("text", 9 bytes), FunctionRef(root:default::demo.mq.md::演示函数)]"#
);
}
#[test]
fn addressable_memory_example_runs_through_the_cli() {
let output = cli(&["run", "examples/memory-buffer.mq.md", "--output", "json"]);
@@ -113,14 +90,14 @@ fn unknown_tool_name_installs_and_dispatches() {
.unwrap()
.as_nanos()
));
let install = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let install = stdlib_support::cli_command()
.args(["tool", "install", "examples/tool-unknown-name/tool.json"])
.env("MARQDO_TOOL_HOME", &home)
.current_dir(repo())
.output()
.unwrap();
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install));
let run = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let run = stdlib_support::cli_command()
.args(["benchmark", "run", "."])
.env("MARQDO_TOOL_HOME", &home)
.current_dir(repo())
@@ -128,7 +105,7 @@ fn unknown_tool_name_installs_and_dispatches() {
.unwrap();
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
assert!(String::from_utf8_lossy(&run.stdout).contains("arg=run"));
let remove = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let remove = stdlib_support::cli_command()
.args(["tool", "remove", "benchmark"])
.env("MARQDO_TOOL_HOME", &home)
.current_dir(repo())
+3 -1
View File
@@ -4,6 +4,8 @@
//! sources, `marqdo lock` records their exact identity, and `check`/`run`
//! compare the current declaration with the lock before using any extension.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
@@ -47,7 +49,7 @@ fn repo() -> PathBuf {
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+4 -2
View File
@@ -5,9 +5,11 @@
//! binary and assert that `check --emit`, `run` and `call` agree.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::process::Output;
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -41,7 +43,7 @@ impl Drop for TempDir {
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+4 -2
View File
@@ -8,6 +8,8 @@
//!
//! Temporary directories live under the OS temp directory and are removed on
//! drop; the repository itself is never modified.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
@@ -75,7 +77,7 @@ impl Drop for TempDir {
/// Run the CLI in `dir`.
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -84,7 +86,7 @@ fn cli(dir: &Path, args: &[&str]) -> Output {
/// Run the CLI in `dir` with one extra environment variable.
fn cli_env(dir: &Path, args: &[&str], key: &str, value: &str) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.env(key, value)
+4 -2
View File
@@ -4,9 +4,11 @@
//! checked-in examples.
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::process::Output;
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -49,7 +51,7 @@ fn repo() -> PathBuf {
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+5 -3
View File
@@ -4,6 +4,8 @@
//! stdout line stream exactly like an external consumer. They cover the P0
//! envelope/lifecycle/byte-fidelity contract and the P1 frame/value policy,
//! plus snapshot equivalence, truncation, live delivery and a broken pipe.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::fs;
use std::io::{BufRead, BufReader, Read};
@@ -51,7 +53,7 @@ impl Drop for TempDir {
}
fn cli(dir: &Path, args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -670,7 +672,7 @@ fn live_chunks_arrive_while_the_program_is_still_running() {
let dir = TempDir::new("live");
let source = "## @exec main\n\n`打印(\"READY\")`\n\n`i = 0`\n\n`while i < 2000000`\n\n`i = i + 1`\n\n`end`\n\n`打印(\"FINISH\")`\n\n`return i`\n";
dir.write("index.mq.md", source);
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let mut child = stdlib_support::cli_command()
.args([
"run",
"index.mq.md",
@@ -723,7 +725,7 @@ fn broken_pipe_makes_the_run_fail_instead_of_running_forever() {
let dir = TempDir::new("pipe");
let source = "## @exec main\n\n`打印(\"START\")`\n\n`i = 0`\n\n`while i < 5000000`\n\n`i = i + 1`\n\n`end`\n\n`return i`\n";
dir.write("index.mq.md", source);
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let mut child = stdlib_support::cli_command()
.args([
"run",
"index.mq.md",
+5 -42
View File
@@ -1,13 +1,11 @@
//! RFC-CM P2 closure lane: C01–C06/C11/C12 in a pure, no-Foreign/no-Plugin host.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
#[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"))
@@ -75,7 +73,7 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
"{criterion} fixture {name} uses forbidden host shortcut `{forbidden}`"
);
}
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let output = stdlib_support::cli_command()
.args([
"run",
path.to_str().unwrap(),
@@ -110,41 +108,6 @@ fn p2_algorithms_run_in_a_pure_no_foreign_no_plugin_host() {
}
}
#[test]
fn p2_stdlib_table_also_runs_in_pure_mode() {
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",
path.to_str().unwrap(),
"--mode",
"pure",
"--output",
"json",
])
.current_dir(&bundle)
.env("MARQDO_STDLIB_DIR", &bundle)
.output()
.expect("run table self-test");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["run"]["status"], "ok");
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("table test list");
assert_eq!(items.len(), 9);
assert_eq!(
items[8]["value"],
"| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |\n| 丙 | 71 |"
);
}
#[test]
fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
let dir = tempfile::tempdir().unwrap();
@@ -154,7 +117,7 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
"## @knowledge 代码\n\n```python\nprint(1)\n```\n\n## @exec main\n\n`return foreign.call(ref(\"#代码\"), None)`\n",
)
.unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let output = stdlib_support::cli_command()
.args([
"run",
foreign.to_str().unwrap(),
@@ -180,7 +143,7 @@ fn foreign_and_plugin_shortcuts_are_unavailable_in_the_pure_lane() {
"## @exec main\n\n`plugin.invoke(\"missing.export\", {})`\n\n`return None`\n",
)
.unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let output = stdlib_support::cli_command()
.args([
"run",
plugin.to_str().unwrap(),
+3 -5
View File
@@ -1,6 +1,8 @@
//! Package instance identity, transitive imports, pinned Git and environment
//! materialization (M0.6 R1/R5).
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
@@ -32,12 +34,8 @@ impl Drop for TempDir {
}
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(binary())
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+5 -3
View File
@@ -1,5 +1,7 @@
//! Isolated plugin worker transport (ADR-0010).
#![cfg(unix)]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
@@ -118,7 +120,7 @@ fn write_manifest(dir: &Path, sha: &str) {
}
fn run(dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args([
"run",
dir.join("doc.mq.md").to_str().unwrap(),
@@ -167,7 +169,7 @@ fn worker_crash_is_isolated_from_the_host() {
"{stderr}"
);
// The host process survived and still runs a native Marqdo program.
let survivor = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let survivor = stdlib_support::cli_command()
.args(["run", "examples/hello.mq.md"])
.current_dir(repo())
.output()
@@ -235,7 +237,7 @@ fn write_capability_manifest(dir: &Path, sha: &str) {
}
fn run_capability(dir: &Path, allow_read: bool) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo"));
let mut command = stdlib_support::cli_command();
command.args([
"run",
dir.join("doc.mq.md").to_str().unwrap(),
+4 -2
View File
@@ -1,7 +1,9 @@
//! Compat-B `打印` routing tests (ADR-0030).
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::process::Output;
struct TempDir(PathBuf);
@@ -25,7 +27,7 @@ impl Drop for TempDir {
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
+4 -1
View File
@@ -15,6 +15,9 @@
//! Other platforms must keep this file compiling but run no provider
//! assertions; the CLI itself fails closed with `ext.platform_unsupported`.
#![cfg(all(target_os = "linux", target_arch = "x86_64"))]
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
@@ -400,7 +403,7 @@ fn marker_text(path: &Path) -> String {
}
fn run_cli(dir: &Path, args: &[&str], marker: &Path) -> Output {
Command::new(cli_binary())
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.env(MARKER_ENV, marker)
+5 -3
View File
@@ -1,11 +1,13 @@
//! End-to-end resource stream tests through the CLI.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::process::{Output, Stdio};
struct TempDir(PathBuf);
@@ -30,7 +32,7 @@ impl Drop for TempDir {
}
fn cli(dir: &Path, args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.output()
@@ -38,7 +40,7 @@ fn cli(dir: &Path, args: &[&str]) -> Output {
}
fn cli_with_stdin(dir: &Path, args: &[&str], input: &[u8]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let mut child = stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.stdin(Stdio::piped())
+2 -3
View File
@@ -4,12 +4,11 @@
//! in the verified `stdlib.json` metadata. There is no `print_override`, no
//! 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::process::Output;
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
@@ -39,7 +38,7 @@ impl Drop for TempDir {
}
fn cli(args: &[&str], dir: &Path, env: &[(&str, &Path)]) -> Output {
let mut command = Command::new(env!("CARGO_BIN_EXE_marqdo"));
let mut command = stdlib_support::cli_command();
command.args(args).current_dir(dir);
for (key, value) in env {
command.env(key, value);
+1 -3
View File
@@ -1,10 +1,8 @@
//! 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 binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
@@ -15,7 +13,7 @@ fn stdlib_dir() -> PathBuf {
}
fn run(dir: &Path, stdlib: &Path, args: &[&str]) -> std::process::Output {
Command::new(binary())
stdlib_support::cli_command()
.args(args)
.current_dir(dir)
.env("MARQDO_STDLIB_DIR", stdlib)
-42
View File
@@ -1,42 +0,0 @@
//! CM-A08/P5 stdlib HTTP framing module tests.
#[path = "support/observation.rs"]
pub mod observation;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
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(&bundle)
.env("MARQDO_STDLIB_DIR", &bundle)
.output()
.expect("run http self-test");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json");
assert_eq!(report["run"]["status"], "ok");
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["decimal"], "200");
assert_eq!(items[1]["value"], "OK");
assert_eq!(items[2]["value"], "text/plain");
assert_eq!(items[3]["value"], "hello world");
assert_eq!(
items[4]["value"],
"POST /echo HTTP/1.1\r\nHost: example.test\r\nContent-Length: 2\r\n\r\nok"
);
assert_eq!(items[5]["decimal"], "200");
assert_eq!(items[6]["value"], "你好");
assert_eq!(items[7]["value"], "POST / HTTP/1.1\r\n\r\nAB");
}
+118 -525
View File
@@ -1,9 +1,11 @@
//! Product-level tests for the whole bundled `marqdo-stdlib` tree.
//! CLI product lane against the accepted external stdlib Bundle (ADR-0070 Phase B).
//!
//! Every public module in `stdlib/README.md` has a `.mq.md` self-test under
//! `stdlib/tests/`, and this lane runs the whole directory through the real
//! user import path (`std:` + the verified bundle), not through a conformance
//! fixture or a Rust shortcut.
//! The standard-library module sources and their self-tests live in the
//! component repositories; this lane proves what the CLI still owns: it loads
//! one verified offline Bundle, resolves the public `std:` surface, and routes
//! the official `print`/`打印` aliases through the ordinary target function.
//! The Bundle is an explicit input (`MARQDO_TEST_STDLIB_BUNDLE`) verified
//! against `tools/stdlib/bundle-pin.json`; there is no in-repo fallback.
#[path = "support/observation.rs"]
pub mod observation;
@@ -11,554 +13,145 @@ pub mod observation;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::{Mutex, MutexGuard};
use std::process::{Command, Output};
static FS_LOCK: Mutex<()> = Mutex::new(());
fn lock_fs(name: &str) -> Option<MutexGuard<'static, ()>> {
if name == "fs.mq.md" {
Some(FS_LOCK.lock().unwrap_or_else(|error| error.into_inner()))
} else {
None
}
}
fn stdlib_dir() -> PathBuf {
stdlib_support::bundle_dir()
}
struct TestFile {
name: String,
stdin: &'static str,
stdout: &'static str,
args: Vec<String>,
env: Vec<(String, String)>,
}
fn product_tests() -> Vec<TestFile> {
let dir = stdlib_dir().join("tests");
let mut files: Vec<TestFile> = std::fs::read_dir(&dir)
.expect("read stdlib tests")
.map(|entry| {
let path = entry.unwrap().path();
if !path.is_file() {
return TestFile {
name: String::new(),
stdin: "",
stdout: "",
args: Vec::new(),
env: Vec::new(),
};
}
let name = path.file_name().unwrap().to_string_lossy().to_string();
let (stdin, stdout) = match name.as_str() {
"console.mq.md" => ("hello\n", ""),
"io.mq.md" => ("", "stdlib self-test\n"),
"stream.mq.md" => ("", "stream\n"),
_ => ("", ""),
};
let text_args = |values: &[&str]| -> Vec<String> {
values.iter().map(|value| value.to_string()).collect()
};
let (args, env) = if name == "fs.mq.md" {
(
text_args(&[
"--allow-read",
"out",
"--allow-read",
"out/**",
"--allow-write",
"out",
"--allow-write",
"out/**",
]),
Vec::new(),
)
} else if name == "env.mq.md" {
(
text_args(&[
"--allow-env",
"MARQDO_TEST_ENV",
"--allow-env",
"MARQDO_MISSING_ENV",
]),
vec![("MARQDO_TEST_ENV".to_string(), "env-value".to_string())],
)
} else if name == "process.mq.md" {
// Use the test binary itself as the granted program: it exists
// on every native platform, unlike the old `/bin/echo` fixture.
let program = env!("CARGO_BIN_EXE_marqdo").to_string();
(
vec![
"--allow-env".to_string(),
"MARQDO_TEST_PROCESS_PROGRAM".to_string(),
"--allow-process".to_string(),
program.clone(),
],
vec![("MARQDO_TEST_PROCESS_PROGRAM".to_string(), program)],
)
} else if name == "random.mq.md" {
(text_args(&["--allow-random"]), Vec::new())
} else {
(Vec::new(), Vec::new())
};
TestFile {
name,
stdin,
stdout,
args,
env,
}
})
.filter(|file| !file.name.is_empty())
.collect();
files.sort_by(|left, right| left.name.cmp(&right.name));
files
}
fn run_product_test(file: &TestFile) -> serde_json::Value {
if file.name == "fs.mq.md" {
let _ = std::fs::remove_dir_all(stdlib_dir().join("tests/out"));
}
let mut child = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(["run"])
.arg(stdlib_dir().join("tests").join(&file.name))
.args(file.args.iter())
.args(["--output", "json"])
.current_dir(stdlib_dir())
.env("MARQDO_STDLIB_DIR", stdlib_dir())
.envs(
file.env
.iter()
.map(|(key, value)| (key.as_str(), value.as_str())),
)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn marqdo");
child
.stdin
.as_mut()
.unwrap()
.write_all(file.stdin.as_bytes())
.unwrap();
let output = child.wait_with_output().expect("wait marqdo");
fn run_fixture(name: &str) -> (serde_json::Value, String) {
let bundle = stdlib_support::bundle_dir();
let fixture = stdlib_support::repo_root()
.join("tests")
.join("product-stdlib")
.join(format!("{name}.mq.md"));
let output: Output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args([
"run",
fixture.to_str().expect("utf-8 fixture path"),
"--output",
"json",
])
.env("MARQDO_STDLIB_DIR", &bundle)
.current_dir(stdlib_support::repo_root())
.output()
.expect("run marqdo");
assert_eq!(
output.status.code(),
Some(0),
"{} failed: {}",
file.name,
"{name} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("json report")
let report: serde_json::Value = serde_json::from_slice(&output.stdout).expect("json report");
assert_eq!(report["run"]["status"], "ok", "{name}");
let stdout = observation::text(&report, "stdout.chunk");
(report, stdout)
}
#[test]
fn every_public_stdlib_module_has_a_product_test() {
let names: Vec<String> = product_tests().into_iter().map(|file| file.name).collect();
assert_eq!(
names,
vec![
"clock.mq.md",
"compress.mq.md",
"console.mq.md",
"csv.mq.md",
"datetime.mq.md",
"demo.mq.md",
"env.mq.md",
"format.mq.md",
"fs.mq.md",
"http.mq.md",
"io.mq.md",
"json.mq.md",
"path.mq.md",
"process.mq.md",
"random.mq.md",
"regex.mq.md",
"stream.mq.md",
"table.mq.md",
"text.mq.md",
"utf8.mq.md",
],
"a public stdlib module is missing a product test"
fn the_accepted_bundle_is_external_and_has_the_required_surface() {
let pin = stdlib_support::BundlePin::committed();
assert!(
pin.source_path.is_none(),
"Phase B: the accepted Bundle must not be vendored in this repository"
);
}
#[test]
fn the_whole_bundled_library_runs_through_std_imports() {
for file in product_tests() {
let _guard = lock_fs(&file.name);
let report = run_product_test(&file);
assert_eq!(report["run"]["status"], "ok", "{}", file.name);
assert_eq!(
observation::text(&report, "stdout.chunk"),
file.stdout,
"{} wrote unexpected stdout",
file.name
let bundle = stdlib_support::bundle_dir();
let manifest: serde_json::Value =
serde_json::from_slice(&std::fs::read(bundle.join("stdlib.json")).unwrap()).unwrap();
assert_eq!(manifest["name"], pin.name);
assert_eq!(manifest["version"], pin.version);
assert_eq!(manifest["digest"], pin.tree_digest);
assert_eq!(manifest["aliases_digest"], pin.aliases_digest);
for required in [
"io.mq.md",
"io/console.mq.md",
"io/stream.mq.md",
"format.mq.md",
"text.mq.md",
"text/utf8.mq.md",
"data/json.mq.md",
"collections/table.mq.md",
"data/table.mq.md",
"fs/file.mq.md",
"path.mq.md",
] {
assert!(
bundle.join(required).is_file(),
"the accepted Bundle is missing {required}"
);
}
}
#[test]
fn fs_test_exercises_the_file_operation_surface() {
let _guard = lock_fs("fs.mq.md");
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "fs.mq.md")
.expect("fs test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "7");
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], "file");
assert_eq!(items[4]["decimal"], "7");
assert_eq!(items[5]["items"][0]["value"], "fs-a.txt");
assert_eq!(items[6]["value"], true);
assert_eq!(items[7]["value"], true);
assert_eq!(items[8]["value"], true);
assert_eq!(items[9]["value"], "你好\n");
assert_eq!(items[10]["decimal"], "7");
assert_eq!(items[11]["value"], "你好\n世界\n");
assert_eq!(items[12]["items"][0]["value"], "fs-b.txt");
assert_eq!(items[13]["value"], true);
assert_eq!(items[14]["value"], true);
assert!(
!stdlib_dir().join("tests/out").exists(),
"the fs test did not remove its directory"
!bundle.join("tests").exists(),
"the accepted Bundle must not ship component self-tests"
);
}
#[test]
fn json_test_parses_and_formats_nested_values() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "json.mq.md")
.expect("json test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "1");
assert_eq!(items[2]["value"], "说\"好");
fn official_print_aliases_match_the_target_function_output() {
let (report, stdout) = run_fixture("print-routing");
assert_eq!(report["run"]["status"], "ok");
let lines: Vec<&str> = stdout.lines().collect();
assert_eq!(lines.len(), 6, "{stdout:?}");
for pair in [(0, 1), (2, 3), (4, 5)] {
assert_eq!(
lines[pair.0], lines[pair.1],
"official alias formatting differs at line {}",
pair.0
);
}
assert_eq!(
items[3]["value"],
"[1, 2.5, -300.0, 0.4, {\"a\": 1.0}, \"x\"]"
lines[0],
r#"["文本", 2, 1.5, [3, true], {a: 1, b: "x"}, None]"#
);
assert_eq!(lines[2], "Table[名称 | 分数]{甲 | 87; 乙 | 92}");
assert_eq!(
lines[4],
r#"[Formula("a = 1"), Code("text", 9 bytes), FunctionRef(root:default::print-routing.mq.md::演示函数)]"#
);
assert_eq!(items[4]["value"], false);
assert_eq!(items[5]["value"], "json.invalid_array");
assert_eq!(items[6]["value"], "json.trailing");
assert_eq!(items[7]["value"], false);
assert_eq!(items[8]["value"], "json.depth");
assert_eq!(items[9]["value"], true);
assert_eq!(items[10]["items"][2]["items"][0]["decimal"], "3");
}
#[test]
fn csv_test_parses_and_formats_quoted_rows() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "csv.mq.md")
.expect("csv test"),
fn std_surface_executes_against_the_official_bundle() {
let (report, stdout) = run_fixture("std-surface");
assert_eq!(stdout, "");
assert_eq!(
observation::terminal(&report)["value"],
serde_json::json!({
"type": "list",
"items": [
{"type": "int", "decimal": "2"},
{"type": "text", "value": "é"},
{"type": "text", "value": "[1, 2]"},
{"type": "text", "value": "[\"ok\", 3]"},
{"type": "text", "value": "a/b"},
{"type": "text", "value": "2026-11-21T08:00:00.123Z"},
{"type": "text", "value": "| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |"}
]
})
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
let row = items[0]["items"].as_array().expect("row");
assert_eq!(row.len(), 3);
assert_eq!(row[0]["value"], "甲");
assert_eq!(row[1]["value"], "乙,丙");
assert_eq!(row[2]["value"], "说\"好");
assert_eq!(items[1]["value"], "甲,\"乙,丙\",\"说\"\"好\"");
let empty = items[2]["items"].as_array().expect("empty row");
assert_eq!(empty.len(), 1);
assert_eq!(empty[0]["value"], "");
assert_eq!(items[3]["value"], "csv.unterminated_quote");
let quoted = items[4]["items"].as_array().expect("quoted row");
assert_eq!(quoted[0]["value"], "a");
assert_eq!(quoted[1]["value"], "b");
assert_eq!(items[5]["value"], true);
let rows = items[6]["items"].as_array().expect("rows");
assert_eq!(rows.len(), 2);
assert_eq!(rows[1]["items"][0]["value"], "说\"好");
assert_eq!(items[7]["value"], "甲,\"乙,丙\"\n\"说\"\"好\",2");
}
#[test]
fn path_test_joins_and_normalizes_project_paths() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "path.mq.md")
.expect("path test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], "a/b/c");
assert_eq!(items[1]["value"], "c.txt");
assert_eq!(items[2]["value"], "a/b");
assert_eq!(items[3]["value"], "txt");
assert_eq!(items[4]["value"], "a/c");
assert_eq!(items[5]["value"], "/a/c");
assert_eq!(items[6]["value"], "../a/b");
assert_eq!(items[7]["value"], true);
assert_eq!(items[8]["value"], false);
}
#[test]
fn regex_test_matches_anchors_classes_and_search() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "regex.mq.md")
.expect("regex test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], false);
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], true);
assert_eq!(items[4]["value"], true);
assert_eq!(items[5]["value"], true);
assert_eq!(items[6]["value"], true);
assert_eq!(items[7]["value"], true);
assert_eq!(items[8]["value"], true);
assert_eq!(items[9]["value"], false);
assert_eq!(items[10]["value"], "regex.invalid");
assert_eq!(items[11]["value"], "regex.unsupported");
assert_eq!(items[12]["value"], true);
assert_eq!(items[13]["value"], true);
let groups = items[14]["items"].as_array().expect("groups");
assert_eq!(groups[0]["value"], "aab");
assert_eq!(groups[1]["value"], "aa");
assert_eq!(groups[2]["value"], "b");
}
#[test]
fn datetime_test_formats_and_parses_utc_instants() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "datetime.mq.md")
.expect("datetime test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], "1970-01-01T00:00:00Z");
assert_eq!(items[1]["value"], "2023-11-14T22:13:20.123Z");
assert_eq!(items[2]["decimal"], "0");
assert_eq!(items[3]["decimal"], "1795248000123");
assert_eq!(items[4]["value"], false);
assert_eq!(items[5]["value"], false);
assert_eq!(items[6]["value"], "1969-12-31T23:59:59.999Z");
}
#[test]
fn clock_test_reports_project_mode_unix_millis() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "clock.mq.md")
.expect("clock test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], "Int");
assert_eq!(items[2]["value"], true);
}
#[test]
fn env_test_reads_only_granted_names() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "env.mq.md")
.expect("env test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], "env-value");
assert_eq!(items[4]["value"], false);
assert_eq!(items[5]["value"], "env.not_found");
}
#[test]
fn process_test_runs_an_explicitly_granted_program() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "process.mq.md")
.expect("process test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "0");
let expected = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.arg("--version")
fn a_missing_explicit_bundle_fails_closed_without_fallback() {
let missing = stdlib_support::repo_root()
.join("target")
.join("does-not-exist-stdlib");
let fixture = stdlib_support::repo_root().join("tests/product-stdlib/std-surface.mq.md");
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args([
"run",
fixture.to_str().expect("utf-8 fixture path"),
"--output",
"json",
])
.env("MARQDO_STDLIB_DIR", &missing)
.current_dir(stdlib_support::repo_root())
.output()
.expect("run marqdo --version");
let expected_stdout = String::from_utf8_lossy(&expected.stdout);
assert_eq!(
items[2]["value"].as_str().expect("process stdout"),
expected_stdout.as_ref(),
"process stdout must match the granted program"
);
assert_eq!(items[3]["value"], "");
}
#[test]
fn random_test_reads_bounded_entropy() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "random.mq.md")
.expect("random test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["decimal"], "16");
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], true);
assert_eq!(items[4]["value"], true);
}
#[test]
fn compress_test_round_trips_gzip_text() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "compress.mq.md")
.expect("compress test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], "hello 世界");
}
#[test]
fn format_test_pins_value_semantics_and_handle_observation() {
let report = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "format.mq.md")
.expect("format test"),
);
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items[0]["decimal"], "3");
assert_eq!(items[1]["value"], "[\"文本\", 2, 1.5]");
assert_eq!(items[2]["value"], "{a: 1}");
assert_eq!(items[3]["value"], "[\"a\", 2]");
assert_eq!(items[4]["value"], "None");
}
#[test]
fn text_and_utf8_tests_agree_on_the_byte_encoding() {
let text = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "text.mq.md")
.expect("text test"),
);
let utf8 = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "utf8.mq.md")
.expect("utf8 test"),
);
assert_eq!(
observation::terminal(&text)["value"]["items"][0]["decimal"],
"2"
);
assert_eq!(
observation::terminal(&text)["value"]["items"][1]["decimal"],
"195"
);
assert_eq!(
observation::terminal(&text)["value"]["items"][2]["decimal"],
"169"
);
assert_eq!(
observation::terminal(&utf8)["value"]["items"][0]["decimal"],
"2"
);
assert_eq!(
observation::terminal(&utf8)["value"]["items"][1]["value"],
"é"
);
assert_eq!(
observation::terminal(&utf8)["value"]["items"][2]["value"],
false
);
}
#[test]
fn stream_and_console_use_the_resource_endpoints() {
let stream = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "stream.mq.md")
.expect("stream test"),
);
assert_eq!(
observation::terminal(&stream)["value"]["items"][0]["value"],
true
);
assert_eq!(
observation::terminal(&stream)["value"]["items"][1]["decimal"],
"7"
);
let console = run_product_test(
product_tests()
.iter()
.find(|file| file.name == "console.mq.md")
.expect("console test"),
);
assert_eq!(
observation::terminal(&console)["value"]["items"][0]["value"],
true
);
assert_eq!(
observation::terminal(&console)["value"]["items"][1]["value"],
"hello"
.expect("run marqdo");
assert_ne!(
output.status.code(),
Some(0),
"an invalid explicit MARQDO_STDLIB_DIR must fail even when a Bundle is installed"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
console["events"]
.as_array()
.unwrap()
.iter()
.any(|event| event["payload"]["operation"] == "resource.read"
|| event["payload"]["operation"] == "resource.open"),
"console test did not go through a resource endpoint"
stderr.contains("stdlib") || stderr.contains("cannot open"),
"failure must name the Bundle: {stderr}"
);
}
-71
View File
@@ -1,71 +0,0 @@
//! CM-A08 table stdlib module tests.
#[path = "support/observation.rs"]
pub mod observation;
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::process::Command;
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(&bundle)
.env("MARQDO_STDLIB_DIR", &bundle)
.output()
.expect("run table self-test");
assert_eq!(
output.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&output.stderr)
);
serde_json::from_slice(&output.stdout).expect("json output")
}
fn rows(value: &serde_json::Value) -> &Vec<serde_json::Value> {
value["rows"].as_array().expect("rows")
}
#[test]
fn stdlib_table_algorithms_rebuild_without_mutating_inputs() {
let report = run_table_self_test();
assert_eq!(report["run"]["status"], "ok");
let items = observation::terminal(&report)["value"]["items"]
.as_array()
.expect("list");
assert_eq!(items.len(), 9);
assert_eq!(items[0]["header"], serde_json::json!(["分数"]));
assert_eq!(items[0]["rows"].as_array().unwrap().len(), 3);
assert_eq!(rows(&items[1]).len(), 2);
assert_eq!(rows(&items[2]).len(), 3);
assert_eq!(rows(&items[2])[0][1]["decimal"], "71");
assert_eq!(rows(&items[3]).len(), 4);
assert_eq!(rows(&items[3])[3][0]["value"], "丁");
assert_eq!(rows(&items[4])[0][1]["decimal"], "99");
assert_eq!(rows(&items[5]).len(), 2);
assert_eq!(items[5]["header"].as_array().unwrap().len(), 4);
assert_eq!(
items[6]["entries"]["a"]["items"].as_array().unwrap().len(),
2
);
assert_eq!(
items[6]["entries"]["b"]["items"].as_array().unwrap().len(),
1
);
// Original input is unchanged.
assert_eq!(rows(&items[7]).len(), 3);
assert_eq!(rows(&items[7])[0][1]["decimal"], "87");
assert_eq!(
items[8]["value"],
"| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |\n| 丙 | 71 |"
);
}
+61 -10
View File
@@ -42,7 +42,9 @@ pub struct BundlePin {
pub name: String,
pub version: String,
pub source_commit: String,
pub source_path: PathBuf,
/// None for the accepted ecosystem Bundle (Phase B): it is not vendored in
/// this repository, so product tests require an explicit verified Bundle.
pub source_path: Option<PathBuf>,
pub tree_digest: String,
pub aliases_digest: String,
}
@@ -70,17 +72,39 @@ impl BundlePin {
let source = value
.get("source")
.unwrap_or_else(|| panic!("Bundle pin {} has no source object", path.display()));
let source_path = source
.get("path")
let source_kind = source
.get("kind")
.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()));
.unwrap_or("in-repo");
let source_path = match source_kind {
"in-repo" => {
let declared = source
.get("path")
.and_then(serde_json::Value::as_str)
.unwrap_or_else(|| {
panic!("in-repo Bundle pin {} has no source.path", path.display())
});
validate_relative(declared).unwrap_or_else(|error| {
panic!("Bundle pin {} source.path: {error}", path.display())
});
Some(PathBuf::from(declared))
}
"ecosystem" => {
for field in ["repository", "commit"] {
required_str(source, field, path);
}
None
}
other => panic!(
"Bundle pin {} has unknown source.kind {other:?}",
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),
source_path,
tree_digest: required_str(&value, "tree_digest", path),
aliases_digest: required_str(&value, "aliases_digest", path),
}
@@ -117,9 +141,16 @@ impl Bundle {
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 root = match (explicit.clone(), pin.source_path.as_ref()) {
(Some(path), _) => path,
(None, Some(relative)) => repo_root().join(relative),
(None, None) => panic!(
"the accepted stdlib Bundle is not vendored in this repository; set \
{BUNDLE_ENV} to a Bundle produced from the pinned ecosystem commit {} \
(tools/ci/fetch_ecosystem_bundle.py)",
pin.source_commit
),
};
let bundle = Self::verify(&root).unwrap_or_else(|error| match &explicit {
Some(_) => panic!(
"{BUNDLE_ENV} does not name a valid stdlib Bundle at {}: {error}",
@@ -252,6 +283,26 @@ pub fn bundle_dir() -> PathBuf {
bundle().root().to_path_buf()
}
/// Bundle root when one is configured, without failing tests that do not need
/// the standard library (Phase B has no in-repo source tree).
pub fn try_bundle_dir() -> Option<PathBuf> {
let pin = BundlePin::committed();
if let Some(explicit) = std::env::var_os(BUNDLE_ENV) {
return Some(PathBuf::from(explicit));
}
pin.source_path.map(|relative| repo_root().join(relative))
}
/// A real CLI command that names the verified Bundle explicitly when one is
/// configured; spawned programs never rely on a compile-time source fallback.
pub fn cli_command() -> std::process::Command {
let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_marqdo"));
if let Some(root) = try_bundle_dir() {
command.env("MARQDO_STDLIB_DIR", root);
}
command
}
/// 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();
@@ -1,4 +1,6 @@
//! C10/P5: a `.mq.md` HTTP client over the TCP resource endpoint.
//! C10/P5: a `.mq.md` program round-trips bytes over the TCP resource endpoint.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
#[path = "support/observation.rs"]
pub mod observation;
@@ -6,7 +8,6 @@ pub mod observation;
use std::io::{Read, Write};
use std::net::TcpListener;
use std::path::Path;
use std::process::Command;
struct TempDir(std::path::PathBuf);
@@ -30,7 +31,11 @@ impl Drop for TempDir {
}
#[test]
fn mqmd_http_client_parses_a_response_from_a_tcp_stream() {
fn a_marqdo_program_round_trips_bytes_over_the_tcp_resource() {
// The CLI owns the TCP resource endpoint; the HTTP domain module now lives in
// the explicit `marqdo-ext-http` package, so this test exercises the generic
// endpoint directly instead of importing a domain module that is not part of
// the default Bundle.
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
@@ -39,17 +44,14 @@ fn mqmd_http_client_parses_a_response_from_a_tcp_stream() {
let count = stream.read(&mut request).unwrap();
assert!(String::from_utf8_lossy(&request[..count]).starts_with("GET / HTTP/1.1\r\n"));
stream
.write_all(
b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello",
)
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello")
.unwrap();
});
let dir = TempDir::new("client");
let dir = TempDir::new("roundtrip");
let program = format!(
r#"---
import:
http: "std:net/http"
编码: "std:text"
---
@@ -57,7 +59,7 @@ import:
`流 = resource.open("tcp", "{address}", ["read", "write"])`
`请求 = http.构建请求("GET", "/", [["Host", "example.test"]], "")`
`请求 = "GET / HTTP/1.1\r\nHost: example.test\r\n\r\n"`
`请求内存 = memory.new(1, 1)`
@@ -85,13 +87,11 @@ import:
`关闭 = resource.close(流)`
`响应 = http.解析响应(响应文本)`
`return [写入.ok, 读出.ok, 响应.状态, 响应.头["Content-Type"], 响应.体, 关闭.ok]`
`return [写入.ok, 写入.value.count == 请求长度, 读出.ok, 数量 > 0, 响应文本, 关闭.ok]`
"#
);
std::fs::write(dir.path().join("index.mq.md"), program).unwrap();
let output = Command::new(env!("CARGO_BIN_EXE_marqdo"))
let output = stdlib_support::cli_command()
.args([
"run",
"index.mq.md",
@@ -101,15 +101,6 @@ import:
"json",
])
.current_dir(dir.path())
.env(
"MARQDO_STDLIB_DIR",
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.join("stdlib"),
)
.output()
.expect("run marqdo");
assert_eq!(
@@ -126,9 +117,12 @@ import:
.expect("list");
assert_eq!(items[0]["value"], true);
assert_eq!(items[1]["value"], true);
assert_eq!(items[2]["decimal"], "200");
assert_eq!(items[3]["value"], "text/plain");
assert_eq!(items[4]["value"], "hello");
assert_eq!(items[2]["value"], true);
assert_eq!(items[3]["value"], true);
assert_eq!(
items[4]["value"],
"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello"
);
assert_eq!(items[5]["value"], true);
server.join().unwrap();
}
+6 -8
View File
@@ -2,6 +2,8 @@
//!
//! The tool fixture is compiled with rustc from `tests/fixtures/tool_echo.rs`
//! rather than a shell script, so these tests run on Windows and macOS too.
#[path = "support/stdlib.rs"]
pub mod stdlib_support;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
@@ -36,12 +38,8 @@ impl Drop for TempDir {
}
}
fn binary() -> &'static str {
env!("CARGO_BIN_EXE_marqdo")
}
fn cli(home: &Path, args: &[&str]) -> Output {
Command::new(binary())
stdlib_support::cli_command()
.args(args)
.env("MARQDO_TOOL_HOME", home)
.output()
@@ -157,7 +155,7 @@ fn independent_sample_tools_consume_public_analysis_and_observation() {
let trace = dir.path().join("trace.json");
let root = repo_root();
let check = Command::new(binary())
let check = stdlib_support::cli_command()
.args([
"check",
"examples/multi-module/index.mq.md",
@@ -169,7 +167,7 @@ fn independent_sample_tools_consume_public_analysis_and_observation() {
.output()
.expect("run check");
assert!(check.status.success(), "check failed: {}", stderr(&check));
let run = Command::new(binary())
let run = stdlib_support::cli_command()
.args([
"run",
"examples/multi-module/index.mq.md",
@@ -354,7 +352,7 @@ fn tampered_binary_and_path_hijack_are_not_executed() {
permissions.set_mode(0o755);
std::fs::set_permissions(&hijack, permissions).unwrap();
}
let output = Command::new(binary())
let output = stdlib_support::cli_command()
.arg("hijack")
.env("MARQDO_TOOL_HOME", &home)
.env("PATH", &path_dir)