diff --git a/.gitignore b/.gitignore index 1ab6813..2058b9a 100755 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ /.integration-work/ /__pycache__/ **/__pycache__/ + +# Local build/cache/scratch (DSH workspace tooling) +/.build/ diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 1ec0bda..6bcc243 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -50,6 +50,8 @@ bash scripts/integration.sh # 生态候选:真实 CLI 制品 + ## 统一 CLI 与制品输入 - 生态候选使用**固定、可验证**的 CLI/Worker/Stdlib 候选制品;输入必须绑定 CLI gitlink SHA、目标平台、归档/二进制/Bundle digest、工具链与锁。 +- 标准库 Bundle 的唯一生产者是根仓库的 `scripts/build-stdlib.py`:它从根提交的精确组件 gitlink 读取各 active `kind = "stdlib"` 组件的 `modules/`,校验发布路径(只发布 `.mq.md`、拒绝 symlink/子模块/大小写与 NFC 冲突、`tests/` 不入库),生成现行 `stdlib.json`(tree digest + aliases digest),配置在 `scripts/stdlib-bundle.json`。版本变化必须显式(`--baseline-manifest` 拒绝同版本不同摘要)。组件仓继续拥有源码与测试,根不复制模块。 +- 组合验收入口是根仓库的 `scripts/acceptance-stdlib.py`:只接受显式 `--cli` 与 `--bundle`(或按根 gitlink 构建),运行各 active 组件的 `entry`、跨仓组合 fixture(别名、Table 切分、默认 Bundle smoke)和必须失败的负例;提供 `--pack-tool` 时用 CLI 自己的打包器做两次确定性打包并核对摘要。CLI 自身打包请使用 Phase A 之后的 `--stdlib-dir` 输入,不再默认读取 CLI 源码树。 - 当前候选的冻结制品适配器以正式 RC.4 为基线,临时从 View 的 `frozen-beta.sh` 获取;这属于待替换的过渡实现,CLI 版本不得由任一消费者决定。主仓库统一制品准备落地后,在此切换并记录证据。 - 组件验收只读取传入制品,不自行下载未知版本;开发目录覆盖入口(如 `MARQDO_STDLIB_DIR`)不得当作发行行为。缺失、摘要不符或平台不符必须拒绝。 diff --git a/docs/MIGRATION.md b/docs/MIGRATION.md index 0fa35f4..1a1d659 100644 --- a/docs/MIGRATION.md +++ b/docs/MIGRATION.md @@ -65,30 +65,90 @@ Conformance 使用 CLI 已固定的真实 fixture 提交。 3. HTTP、Regex、Archive 的真实替代和授权回归先行。候选同时移除 CLI 中旧领域宿主服务和旧导入。 4. 验证同输入两次组装结果、摘要及路径负例、C1/C2/C3、独立冷安装和真实工具集成后,再切换基础发行。当前状态为 UNVERIFIED。 -## 现行 CLI 标准库迁移归属 +## 标准库源码归位迁移(marqdo#9,2026-11-26 M0 冻结) -| CLI 当前路径 | 唯一目标组件 | 新 Bundle 路径 / 处理 | -|---|---|---| -| `clock.mq.md` | std-system | `system/clock.mq.md` | -| `compress.mq.md` | archive 扩展 | 不入最终标准库;先建立等价扩展与替代后端再删除宿主 convenience service | -| `data/csv.mq.md` | std-data | `data/csv.mq.md` | -| `data/json.mq.md` | std-data | `data/json.mq.md` | -| `data/table.mq.md` | std-collections + std-data(函数级切分) | 集合算法 `collections/table.mq.md`;GFM 序列化 `data/gfm.mq.md`;不复制函数 | -| `datetime.mq.md` | std-system | `system/datetime.mq.md`(UTC/基础日历) | -| `demo.mq.md` | std-io 的 examples 或主仓库综合示例(择一) | 不作为公开安装模块;若只是 IO 自测,归 std-io | -| `env.mq.md` | std-system | `system/env.mq.md` | -| `format.mq.md` | std-io | `io/format.mq.md` | -| `fs/file.mq.md` | std-fs | `fs/file.mq.md` | -| `io.mq.md` | std-io | `io/index.mq.md`;官方 print alias 指向唯一权威 `写值`(迁移时同步生成元数据) | -| `io/console.mq.md` | std-io | `io/console.mq.md` | -| `io/stream.mq.md` | std-io | `io/stream.mq.md` | -| `net/http.mq.md` | http 扩展 | 转为普通 Package 的 HTTP 实现,依赖 std-net;保持报文算法及真实 TCP 对照测试 | -| `path.mq.md` | std-fs | `fs/path.mq.md` | -| `process.mq.md` | std-system | `system/process.mq.md` | -| `random.mq.md` | std-system | `system/random.mq.md` | -| `regex.mq.md` | regex 扩展 | 单一正则模块,迁移纯子集及外部引擎;替换后删除核心宿主服务 | -| `text.mq.md` | std-text | 重复 UTF-8 实现合并入 `text/utf8.mq.md`;新增通用 `text/text.mq.md` 不复制 encoder | -| `text/utf8.mq.md` | std-text | `text/utf8.mq.md`(唯一权威 encoder/decoder) | +本节是标准库迁出的**唯一现行台账**,取代此前按未来目录规划起草的路径表(如 `system/clock.mq.md`、`io/index.mq.md`);旧路径方案会改变公开 `std:` 路径,与“迁移不改语言/库语义”冲突,已作废。详细实施与验收见父仓工单 [marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9),各接收仓子工单在对应仓库 issue #1。 + +### 基线与身份(M0) + +| 对象 | 权威身份 | +| --- | --- | +| 根仓库 | `cflmy/marqdo@484cb10d66db9b92f0527499642ae6abddb3ef29` | +| CLI 标准库源 | `cflmy/marqdo-cli@452e9a32bd9e40dba427d4180691c58bab74449e`(RC.4 发行组合;`stdlib/` 自 `4bbefc9` 起未变) | +| 迁移前 Bundle | `marqdo-stdlib@0.1.0`,tree digest `sha256:5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713`(含 `tests/`) | +| 公开函数台账 | 20 个模块、151 个 H2 函数,由基线 Bundle 上 `marqdo inspect --signature` 生成并记入各接收仓工单 | +| CLI 显式 Bundle 输入 | [marqdo-cli#11](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11) Phase A(PR #12)已提供 `--stdlib-dir`/pin 校验;Phase B(删除仓内源树)以本台账根组合验收为前置 | + +### 模块归属与冻结发布路径 + +接收仓库负责源码、测试和后续缺陷;根只做组合、锁定和验收。`modules/` 镜像 Bundle 根相对路径,只收模块不收 `tests/`;官方 manifest 由根唯一生产者生成。 + +| 原 CLI 路径(相对 `stdlib/`) | 接收仓 / 工单 | 冻结发布路径(Bundle 根相对) | 公开函数 | +| --- | --- | --- | --- | +| `clock.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `clock.mq.md` | 1 | +| `datetime.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `datetime.mq.md` | 14 | +| `env.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `env.mq.md` | 2 | +| `process.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `process.mq.md` | 1 | +| `random.mq.md` | [std-system#1](https://git.cflmy.cn/cflmy/marqdo-std-system/issues/1) | `random.mq.md` | 2 | +| `format.mq.md` | [std-io#1](https://git.cflmy.cn/cflmy/marqdo-std-io/issues/1) | `format.mq.md` | 8 | +| `io.mq.md` | [std-io#1](https://git.cflmy.cn/cflmy/marqdo-std-io/issues/1) | `io.mq.md` | 5 | +| `io/console.mq.md` | [std-io#1](https://git.cflmy.cn/cflmy/marqdo-std-io/issues/1) | `io/console.mq.md` | 4 | +| `io/stream.mq.md` | [std-io#1](https://git.cflmy.cn/cflmy/marqdo-std-io/issues/1) | `io/stream.mq.md` | 3 | +| `data/json.mq.md` | [std-data#1](https://git.cflmy.cn/cflmy/marqdo-std-data/issues/1) | `data/json.mq.md` | 22 | +| `data/csv.mq.md` | [std-data#1](https://git.cflmy.cn/cflmy/marqdo-std-data/issues/1) | `data/csv.mq.md` | 7 | +| `data/table.mq.md` | [std-collections#1](https://git.cflmy.cn/cflmy/marqdo-std-collections/issues/1) / [std-data#1](https://git.cflmy.cn/cflmy/marqdo-std-data/issues/1) | `collections/table.mq.md`(8 个值操作)/ `data/table.mq.md`(4 个序列化) | 12 | +| `fs/file.mq.md` | [std-fs#1](https://git.cflmy.cn/cflmy/marqdo-std-fs/issues/1) | `fs/file.mq.md` | 14 | +| `path.mq.md` | [std-fs#1](https://git.cflmy.cn/cflmy/marqdo-std-fs/issues/1) | `path.mq.md` | 8 | +| `text.mq.md` | [std-text#1](https://git.cflmy.cn/cflmy/marqdo-std-text/issues/1) | `text.mq.md`(`utf8编码` 薄封装) | 1 | +| `text/utf8.mq.md` | [std-text#1](https://git.cflmy.cn/cflmy/marqdo-std-text/issues/1) | `text/utf8.mq.md`(唯一编解码实现) | 10 | +| `net/http.mq.md` | [ext-http#1](https://git.cflmy.cn/cflmy/marqdo-ext-http/issues/1) | 显式 Package 模块,**不进入默认 Bundle**,不再是 `std:` | 11 | +| `regex.mq.md` | [ext-regex#1](https://git.cflmy.cn/cflmy/marqdo-ext-regex/issues/1) | 显式 Package 模块,**不进入默认 Bundle**,不再是 `std:` | 22 | +| `compress.mq.md` | [ext-archive#1](https://git.cflmy.cn/cflmy/marqdo-ext-archive/issues/1) | 显式 Package 模块,**不进入默认 Bundle**,不再是 `std:` | 2 | +| `demo.mq.md` | 不设接收仓;根 Bundle 组合 fixture | 不作为公开安装模块 | 2 | + +`std-core`、`std-encoding`、`std-net` 没有与之对应的旧模块:本轮不发空工单、不激活、不要求补齐未来规划;若已实现模块被本期 Bundle 实际依赖,再按真实依赖补充工单。 + +### 原测试断言归属 + +每项必须在新归属留下真实执行证据;跨模块断言归根 Bundle 组合测试。 + +| 原 `stdlib/tests/` 文件 | 接收仓 | 断言载体 | +| --- | --- | --- | +| `clock.mq.md`、`datetime.mq.md`、`env.mq.md`、`process.mq.md`、`random.mq.md` | std-system | 组件 case,覆盖原 Rust 断言 | +| `console.mq.md`、`format.mq.md`、`io.mq.md`、`stream.mq.md` | std-io | 组件 case + resource 端点事件检查 | +| `csv.mq.md`、`json.mq.md` | std-data | 组件 case,覆盖原 Rust 断言 | +| `table.mq.md` | std-collections(值操作)+ std-data(GFM)+ 根组合 | 切分后的组件 case 与根组合用例 | +| `fs.mq.md`、`path.mq.md` | std-fs | 组件 case,覆盖原 Rust 断言 | +| `text.mq.md`、`utf8.mq.md` | std-text | 组件 case,覆盖原 Rust 断言 | +| `http.mq.md` | ext-http | 领域回归(基线仅运行级覆盖,需补真实断言) | +| `regex.mq.md` | ext-regex | 领域回归,覆盖原 Rust 断言 | +| `compress.mq.md` | ext-archive | 领域回归,覆盖原 Rust 断言 | +| `demo.mq.md` | 根 Bundle 组合测试 | 组合运行证据 | + +### 决策与取舍 + +1. **冻结路径**:以 Bundle 根相对路径为公开身份,迁移不改 `std:` 导入路径;被旧台账规划改名(如 `system/clock.mq.md`、`io/index.mq.md`)的条目按本表冻结。 +2. **测试不随发行**:`tests/` 迁入组件仓并留在仓库外,默认 Bundle 只含模块;因此 Bundle 内容必然变化,版本与 digest 由 MIG-BUNDLE 唯一生产者显式更新,摘要算法不变。 +3. **Table 切分**:值操作以 `std:collections/table` 为唯一权威,GFM 序列化以 `std:data/table` 为唯一权威;不保留旧 `std:data/table` 的值操作兼容转发,已知消费者在同一候选内更新。 +4. **Text 去重**:UTF-8 编解码唯一实现在 `text/utf8.mq.md`,`text.mq.md#utf8编码` 为保留公开名称的薄封装。 +5. **IO 别名**:`io.mq.md` 保持官方 `print`/`打印` 的别名目标 `写值`,签名与 effects 不变;别名元数据仍由 Bundle 生产者生成。 +6. **三个领域模块**:HTTP/Regex/Archive 迁入既有扩展仓并退出默认 Bundle,不保留隐藏的 `std:` fallback;CLI 现有 `regex.*`/`compress.*` 宿主请求是历史例外,本轮不删除也不新增同类请求,彻底消除另开工单。 +7. **`demo.mq.md`**:不作为公开库模块,转为根 Bundle 组合 fixture,避免为了放置文件创建无独立责任的新仓库。 +8. **staging 不是发行**:迁移期为了隔离测试,允许用基线 Bundle 覆盖组件模块并重算 digest 的 staging 组合;它不是官方发布源,最终只有根唯一生产路径。 +9. **CLI 侧最小修改**:Phase A 显式制品输入已落地;Phase B 删除仓内官方源树只在组件替代与根组合验收通过后执行,不同时进行核心重构。 +10. **未创建的新仓**:不为缺失模块创建同名替代仓;`marqdo-stdlib` 聚合仓仍未建立,聚合治理按原独立计划推进,不阻塞本次源码归位。 + +### 迁移状态 + +| 项 | 状态 | 证据 | +| --- | --- | --- | +| M0 盘点与派单 | 完成 | 本节、9 个接收仓 issue #1、[marqdo#9](https://git.cflmy.cn/cflmy/marqdo/issues/9) 评论 | +| 组件接收(源码+断言) | 候选已推送(6 个 std 仓) | [std-text PR #2](https://git.cflmy.cn/cflmy/marqdo-std-text/pulls/2)、[std-system PR #2](https://git.cflmy.cn/cflmy/marqdo-std-system/pulls/2)、[std-io PR #2](https://git.cflmy.cn/cflmy/marqdo-std-io/pulls/2)、[std-fs PR #2](https://git.cflmy.cn/cflmy/marqdo-std-fs/pulls/2)、[std-data PR #2](https://git.cflmy.cn/cflmy/marqdo-std-data/pulls/2)、[std-collections PR #2](https://git.cflmy.cn/cflmy/marqdo-std-collections/pulls/2) | +| 领域模块(http/regex/archive) | 未开始 | ext-http/ext-regex/ext-archive issue #1 | +| Bundle 唯一生产者 | 脚本与契约测试已落地,待根候选验收 | `scripts/build-stdlib.py`、`scripts/stdlib-bundle.json`、`tests/integration/test_build_stdlib.py` | +| 组合验收入口 | 已落地,待根候选执行 | `scripts/acceptance-stdlib.py`、`tests/integration/composition/` | +| CLI 旧源树删除 | 未开始(等待根组合验收) | [marqdo-cli#11](https://git.cflmy.cn/cflmy/marqdo-cli/issues/11) Phase B | +| 根组合与切换 | 未开始 | 本仓 MIG-RELEASE 候选 | ## v2 功能历史索引 diff --git a/docs/REPOSITORY-TASKS.md b/docs/REPOSITORY-TASKS.md index 1d01e10..c5140d7 100644 --- a/docs/REPOSITORY-TASKS.md +++ b/docs/REPOSITORY-TASKS.md @@ -35,7 +35,7 @@ ## 标准库 -每个仓库交付可独立测试的模块,共同组成默认 Bundle。聚合仓库 `marqdo-stdlib` 尚未创建,九个 `std-*` 当前保持根 catalog 的 planned 直属记录;CLI 内置标准库仍是现行发行权威,迁移完成前不得声称拆分完成。 +每个仓库交付可独立测试的模块,共同组成默认 Bundle。聚合仓库 `marqdo-stdlib` 尚未创建,九个 `std-*` 当前保持根 catalog 的 planned 直属记录;CLI 内置标准库仍是现行发行权威,迁移完成前不得声称拆分完成。迁移的基线、模块/函数与断言台账、冻结发布路径见 [迁移台账](MIGRATION.md) 的“标准库源码归位迁移”一节;唯一 Bundle 生产者是根 `scripts/build-stdlib.py`,组合验收入口是 `scripts/acceptance-stdlib.py`。 | 仓库 | 要完成的任务 | | --- | --- | diff --git a/scripts/acceptance-stdlib.py b/scripts/acceptance-stdlib.py new file mode 100755 index 0000000..bd20407 --- /dev/null +++ b/scripts/acceptance-stdlib.py @@ -0,0 +1,360 @@ +#!/usr/bin/env python3 +"""Accept the stdlib migration candidate with explicit, verified inputs. + +This is the root-layer composition gate: it builds (or accepts) the one Bundle +produced by ``scripts/build-stdlib.py`` from the pinned component gitlinks, runs +each active stdlib component's own entry point against that Bundle, runs the +cross-repository composition fixtures, exercises the negative inputs that must +fail closed, and optionally packages the Bundle with the CLI's own packer twice +to prove determinism. + +Every input is explicit: a real ``marqdo`` executable (``--cli``) and either a +Bundle (``--bundle``) or a checkout that can build one at its pinned gitlinks. +Nothing is downloaded and no sibling component is discovered implicitly. + +Usage: + + python3 scripts/acceptance-stdlib.py --cli build/marqdo --work build/accept + python3 scripts/acceptance-stdlib.py --cli build/marqdo --work build/accept \ + --pack-tool /path/to/cli/tools/pack-stdlib.py --evidence build/accept/evidence.json +""" + +from __future__ import annotations + +import argparse +import base64 +import hashlib +import json +import os +import shutil +import subprocess +import sys +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +CASES = ROOT / "tests" / "integration" / "composition" / "cases" +CASES_SCHEMA = "marqdo.stdlib-test-case" +FORBIDDEN = { + "net/http.mq.md", + "regex.mq.md", + "compress.mq.md", + "demo.mq.md", + "tests", +} + + +class AcceptanceError(Exception): + pass + + +def run(command, cwd=None, env=None, input_bytes=b""): + result = subprocess.run( + command, cwd=cwd, env=env, input=input_bytes, capture_output=True + ) + return result + + +def sha256(path: Path) -> str: + return "sha256:" + hashlib.sha256(path.read_bytes()).hexdigest() + + +def channel_text(events: list[dict], channel: str) -> str: + chunks = [] + for event in events: + if event.get("kind") != channel: + continue + payload = event["payload"] + data = base64.b64decode(payload["data_base64"]) + if len(data) != payload["byte_count"]: + raise AcceptanceError(f"{channel} byte_count mismatch") + chunks.append(data) + return b"".join(chunks).decode("utf-8") + + +def tree_digest(bundle: Path) -> str: + digest = hashlib.sha256() + for path in sorted(bundle.rglob("*.mq.md"), key=lambda p: p.relative_to(bundle).as_posix()): + digest.update(path.relative_to(bundle).as_posix().encode()) + digest.update(b"\0") + digest.update(path.read_bytes()) + digest.update(b"\0") + return "sha256:" + digest.hexdigest() + + +def aliases_digest(aliases: list[dict]) -> str: + digest = hashlib.sha256() + for alias in sorted(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 "sha256:" + digest.hexdigest() + + +def verify_bundle(bundle: Path) -> dict: + manifest_path = bundle / "stdlib.json" + if not manifest_path.is_file(): + raise AcceptanceError(f"missing Bundle manifest: {manifest_path}") + manifest = json.loads(manifest_path.read_text()) + for field in ("name", "version", "digest", "aliases_digest"): + if not isinstance(manifest.get(field), str) or not manifest[field]: + raise AcceptanceError(f"manifest has no {field}") + computed = tree_digest(bundle) + if computed != manifest["digest"]: + raise AcceptanceError( + f"manifest digest mismatch: {manifest['digest']} != {computed}" + ) + aliases = manifest.get("public_aliases", []) + expected_alias = aliases_digest(aliases) + if expected_alias != manifest["aliases_digest"]: + raise AcceptanceError("aliases digest mismatch") + files = sorted( + path.relative_to(bundle).as_posix() + for path in bundle.rglob("*.mq.md") + ) + for relative in files: + parts = relative.split("/") + if "tests" in parts or relative in FORBIDDEN: + raise AcceptanceError(f"forbidden module in Bundle: {relative}") + for alias in aliases: + if alias["target_module"] not in files: + raise AcceptanceError( + f"public alias targets missing module {alias['target_module']}" + ) + if "io.mq.md" not in files: + raise AcceptanceError("Bundle lost the io.mq.md alias target") + return { + "manifest": manifest, + "files": files, + "tree_digest": computed, + } + + +def run_case(cli: str, bundle: Path, case: dict) -> dict: + source = ROOT / "tests" / "integration" / "composition" / case["file"] + command = [cli, "run", str(source), *case.get("args", []), "--output", "json"] + env = os.environ.copy() + env["MARQDO_STDLIB_DIR"] = str(bundle) + for key, value in case.get("env", {}).items(): + env[key] = value.replace("$MARQDO_BIN", cli) + result = run(command, cwd=ROOT, env=env, input_bytes=case.get("stdin", "").encode()) + if result.returncode != 0: + raise AcceptanceError( + f"composition case {case['name']} failed: " + f"{result.stderr.decode(errors='replace')}" + ) + report = json.loads(result.stdout) + if report.get("run", {}).get("status") != "ok": + raise AcceptanceError(f"composition case {case['name']} run status not ok") + terminal = report["events"][-1]["payload"] + if terminal.get("value") != case["expected_terminal"]: + raise AcceptanceError( + f"composition case {case['name']} terminal value changed" + ) + stdout = channel_text(report["events"], "stdout.chunk") + if stdout != case.get("expected_stdout", ""): + raise AcceptanceError( + f"composition case {case['name']} stdout changed: {stdout!r}" + ) + return {"name": case["name"], "status": "PASS"} + + +def load_components() -> list[dict]: + catalog = tomllib.loads((ROOT / "components.toml").read_text()) + return [ + component + for component in catalog["component"] + if component.get("kind") == "stdlib" and component.get("state") == "active" + ] + + +def component_gates(cli: str, bundle: Path) -> list[dict]: + results = [] + for component in load_components(): + entry = ROOT / component["path"] / component["entry"] + if not entry.is_file(): + raise AcceptanceError( + f"active component {component['id']} has no entry {component['entry']}" + ) + env = os.environ.copy() + env["MARQDO_BIN"] = cli + env["MARQDO_STDLIB_DIR"] = str(bundle) + result = run([str(entry)], cwd=entry.parent.parent, env=env) + output = (result.stdout + result.stderr).decode(errors="replace").strip() + if result.returncode != 0: + raise AcceptanceError( + f"component {component['id']} failed entry {component['entry']}:\n{output}" + ) + results.append( + { + "id": component["id"], + "entry": component["entry"], + "status": "PASS", + "output": output, + } + ) + return results + + +def negative_gates(cli: str, bundle: Path, work: Path) -> list[dict]: + results = [] + + def expect_failure(name, command): + result = run(command) + if result.returncode == 0: + raise AcceptanceError(f"negative gate {name} unexpectedly passed") + results.append( + { + "name": name, + "status": "PASS", + "exit": result.returncode, + "stderr": result.stderr.decode(errors="replace").strip()[:400], + } + ) + + missing = work / "missing-bundle" + env = os.environ.copy() + env["MARQDO_STDLIB_DIR"] = str(missing) + expect_failure( + "missing-explicit-bundle", + [cli, "run", str(ROOT / "tests/integration/composition/default-bundle.mq.md")], + ) + + tampered = work / "tampered-bundle" + if tampered.exists(): + shutil.rmtree(tampered) + shutil.copytree(bundle, tampered) + target = next(iter(sorted(tampered.rglob("*.mq.md")))) + target.write_bytes(target.read_bytes() + b"\n") + env["MARQDO_STDLIB_DIR"] = str(tampered) + expect_failure( + "tampered-module-digest", + [cli, "run", str(ROOT / "tests/integration/composition/default-bundle.mq.md")], + ) + return results + + +def packaging_gates(pack_tool: str, bundle: Path, work: Path) -> list[dict]: + results = [] + archives = [] + for attempt in (1, 2): + out_dir = work / f"pack-{attempt}" + if out_dir.exists(): + shutil.rmtree(out_dir) + result = run( + [ + sys.executable, + pack_tool, + "--stdlib-dir", + str(bundle), + "--out-dir", + str(out_dir), + ] + ) + if result.returncode != 0: + raise AcceptanceError( + "CLI packer rejected the Bundle: " + + result.stderr.decode(errors="replace") + ) + archives.append(sorted(out_dir.glob("*.tar.gz"))[0]) + if archives[0].read_bytes() != archives[1].read_bytes(): + raise AcceptanceError("two packaging runs are not byte-identical") + descriptor = json.loads( + sorted(archives[0].parent.glob("*.json"))[0].read_text() + ) + results.append( + { + "status": "PASS", + "archive": archives[0].name, + "archive_sha256": sha256(archives[0]), + "tree_digest": descriptor.get("tree_digest"), + "aliases_digest": descriptor.get("aliases_digest"), + "deterministic": True, + } + ) + return results + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--cli", required=True) + parser.add_argument("--work", required=True) + parser.add_argument("--bundle") + parser.add_argument("--pack-tool") + parser.add_argument("--evidence") + parser.add_argument("--root-commit") + args = parser.parse_args(argv) + cli = str(Path(args.cli).resolve()) + if not Path(cli).is_file(): + raise SystemExit(f"acceptance-stdlib: error: no CLI executable at {cli}") + work = Path(args.work).resolve() + work.mkdir(parents=True, exist_ok=True) + try: + if args.bundle: + bundle = Path(args.bundle).resolve() + else: + bundle = work / "bundle" + if bundle.exists(): + shutil.rmtree(bundle) + command = [ + sys.executable, + str(ROOT / "scripts" / "build-stdlib.py"), + "--out", + str(bundle), + ] + if args.root_commit: + command += ["--root-commit", args.root_commit] + result = run(command, cwd=ROOT) + if result.returncode != 0: + raise AcceptanceError( + "Bundle producer failed: " + + result.stderr.decode(errors="replace") + ) + bundle_record = verify_bundle(bundle) + version = run([cli, "--version"]).stdout.decode().strip() + cases = [] + for path in sorted(CASES.glob("*.json")): + case = json.loads(path.read_text()) + if case.get("schema") != CASES_SCHEMA: + raise AcceptanceError(f"unsupported case schema: {path}") + cases.append(run_case(cli, bundle, case)) + components = component_gates(cli, bundle) + negatives = negative_gates(cli, bundle, work) + packaging = ( + packaging_gates(args.pack_tool, bundle, work) + if args.pack_tool + else [] + ) + evidence = { + "schema": "marqdo.stdlib-acceptance", + "schema_version": 1, + "cli": {"path": cli, "version": version, "sha256": sha256(Path(cli))}, + "root_commit": run( + ["git", "-C", str(ROOT), "rev-parse", "HEAD"] + ).stdout.decode().strip(), + "bundle": { + "name": bundle_record["manifest"]["name"], + "version": bundle_record["manifest"]["version"], + "tree_digest": bundle_record["tree_digest"], + "aliases_digest": bundle_record["manifest"]["aliases_digest"], + "files": bundle_record["files"], + }, + "components": components, + "composition": cases, + "negatives": negatives, + "packaging": packaging, + "status": "PASS", + } + except AcceptanceError as error: + print(f"acceptance-stdlib: FAIL: {error}", file=sys.stderr) + return 1 + text = json.dumps(evidence, ensure_ascii=False, indent=2) + "\n" + if args.evidence: + Path(args.evidence).write_text(text) + print(text) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/scripts/build-stdlib.py b/scripts/build-stdlib.py new file mode 100755 index 0000000..4c78242 --- /dev/null +++ b/scripts/build-stdlib.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Build the one official `marqdo-stdlib` Bundle from pinned component gitlinks. + +The producer owns composition only: it collects the published `modules/` files +of every **active** `kind = "stdlib"` component at the exact commit pinned by +the root Gitlink, validates the published path set, generates the current +`stdlib.json` (tree digest + public aliases digest) and writes a deterministic +Bundle directory. Component repositories keep the module sources and tests; the +root repository does not copy or edit them. The CLI packages the resulting +Bundle with its existing `tools/pack-stdlib.py`. + +Identity rules: + +* release mode (default) reads `components.toml`, the Bundle config and the + gitlinks from the ``--root-commit`` tree, never from the working tree; +* `--worktree` is a development-only mode that reads each component's + ``HEAD`` and requires a clean component checkout; +* only ``modules/**/*.mq.md`` is published. Other files under ``modules/`` + (for example ``modules/README.md``) stay repository documentation and are + not packed. Symlinks, submodules and non-regular entries are refused; +* published paths must be NFC, case-insensitively unique and free of + ``tests/``, ``.git`` or traversal segments; +* a version bump is explicit: with ``--baseline-manifest`` content digest + changes are refused unless ``version`` also changes. + +Usage: + + python3 scripts/build-stdlib.py --out build/stdlib + python3 scripts/build-stdlib.py --out build/stdlib --worktree + python3 scripts/build-stdlib.py --out build/stdlib \ + --baseline-manifest previous/stdlib.json +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import shutil +import subprocess +import sys +import tempfile +import tomllib +import unicodedata +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_CONFIG = Path("scripts") / "stdlib-bundle.json" +MANIFEST = "stdlib.json" +MODULES = "modules" +PUBLISHED_SUFFIX = ".mq.md" + + +class BundleError(Exception): + """An input cannot become the official Bundle.""" + + +def _git(repo: Path, *args: str) -> bytes: + result = subprocess.run( + ["git", "-C", str(repo), *args], capture_output=True + ) + if result.returncode != 0: + raise BundleError( + f"git failed in {repo}: {' '.join(args)}: " + f"{result.stderr.decode(errors='replace').strip()}" + ) + return result.stdout + + +def _nfc(value: str) -> str: + return unicodedata.normalize("NFC", value) + + +def load_json(path: Path) -> dict: + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError) as error: + raise BundleError(f"cannot read {path}: {error}") from error + if not isinstance(data, dict): + raise BundleError(f"{path} must contain a JSON object") + return data + + +def read_blob(repo: Path, revision: str, path: str) -> bytes | None: + result = subprocess.run( + ["git", "-C", str(repo), "show", f"{revision}:{path}"], + capture_output=True, + ) + return result.stdout if result.returncode == 0 else None + + +def read_catalog(root: Path, revision: str | None) -> list[dict]: + if revision is None: + raw = (root / "components.toml").read_bytes() + else: + raw = read_blob(root, revision, "components.toml") + if raw is None: + raise BundleError(f"root commit {revision} has no components.toml") + try: + catalog = tomllib.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, tomllib.TOMLDecodeError) as error: + raise BundleError(f"invalid components.toml: {error}") from error + components = catalog.get("component") + if not isinstance(components, list): + raise BundleError("components.toml has no [[component]] entries") + return components + + +def read_config(root: Path, revision: str | None, path: Path) -> dict: + if not path.is_absolute(): + path = root / path + if revision is not None: + relative = path.resolve().relative_to(root.resolve()).as_posix() + raw = read_blob(root, revision, relative) + if raw is None: + raise BundleError(f"root commit {revision} has no {relative}") + try: + config = json.loads(raw.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise BundleError(f"invalid Bundle config {relative}: {error}") from error + else: + config = load_json(path) + for field in ("name", "version"): + value = config.get(field) + if not isinstance(value, str) or not value: + raise BundleError(f"Bundle config has no non-empty `{field}`") + aliases = config.get("public_aliases", []) + if not isinstance(aliases, list): + raise BundleError("Bundle config `public_aliases` must be a list") + return config + + +def pinned_gitlink(root: Path, revision: str, path: str) -> str: + result = _git(root, "ls-tree", revision, "--", path).decode().strip() + if not result: + raise BundleError( + f"root commit {revision} has no gitlink at {path}; only published " + "components may join the Bundle" + ) + fields = result.split() + if len(fields) != 4: + raise BundleError(f"invalid gitlink record for {path}") + mode, kind, sha, _ = fields + if mode != "160000" or kind != "commit": + raise BundleError(f"{path} is not a gitlink in root commit {revision}") + return sha + + +def worktree_sha(component_dir: Path) -> str: + if not (component_dir / ".git").exists(): + raise BundleError(f"missing component checkout: {component_dir}") + status = _git(component_dir, "status", "--porcelain").decode().strip() + if status: + raise BundleError(f"dirty component checkout: {component_dir}") + return _git(component_dir, "rev-parse", "HEAD").decode().strip() + + +def validate_published_path(relative: str, component_id: str) -> None: + if not relative or relative.startswith("/"): + raise BundleError(f"{component_id}: invalid published path {relative!r}") + parts = relative.split("/") + if any(part in ("", ".", "..") for part in parts): + raise BundleError(f"{component_id}: unsafe published path {relative!r}") + if any(part.startswith(".") for part in parts): + raise BundleError(f"{component_id}: hidden path segment in {relative!r}") + if "tests" in parts: + raise BundleError(f"{component_id}: tests must not enter the Bundle: {relative!r}") + if not relative.endswith(PUBLISHED_SUFFIX): + raise BundleError( + f"{component_id}: only {PUBLISHED_SUFFIX} files are published, got {relative!r}" + ) + if _nfc(relative) != relative: + raise BundleError( + f"{component_id}: published path is not NFC normalised: {relative!r}" + ) + + +def component_modules(component_dir: Path, revision: str, component_id: str) -> list[tuple[str, str]]: + output = _git( + component_dir, "ls-tree", "-r", "-z", revision, "--", MODULES + ) + records = [record for record in output.split(b"\0") if record] + published: list[tuple[str, str]] = [] + for record in records: + header, _, raw_path = record.partition(b"\t") + fields = header.decode().split() + if len(fields) != 3: + raise BundleError(f"{component_id}: invalid tree record {record!r}") + mode, kind, sha = fields + path = raw_path.decode() + if kind != "blob" or mode not in ("100644", "100755"): + raise BundleError( + f"{component_id}: only regular modules files are publishable, " + f"found {mode} {kind} at {path}" + ) + relative = path[len(MODULES) + 1 :] + if not relative.endswith(PUBLISHED_SUFFIX): + continue + validate_published_path(relative, component_id) + published.append((relative, sha)) + if not published: + raise BundleError( + f"{component_id}: active component publishes no {PUBLISHED_SUFFIX} modules" + ) + return published + + +def collect(root: Path, components: list[dict], *, root_commit: str | None) -> tuple[dict[str, bytes], list[dict]]: + active = [ + component + for component in components + if component.get("kind") == "stdlib" and component.get("state") == "active" + ] + if not active: + raise BundleError("no active stdlib component; nothing to publish") + for component in active: + if component.get("release") != "base": + raise BundleError( + f'{component["id"]}: active stdlib component must have release = "base"' + ) + files: dict[str, bytes] = {} + identities: list[dict] = [] + owners: dict[str, str] = {} + folded: dict[str, str] = {} + for component in active: + component_id = component["id"] + path = component["path"] + component_dir = (root / path).resolve() + revision = ( + pinned_gitlink(root, root_commit, path) + if root_commit is not None + else worktree_sha(component_dir) + ) + modules = component_modules(component_dir, revision, component_id) + for relative, sha in modules: + key = _nfc(relative).casefold() + if relative in owners: + raise BundleError( + f"duplicate published path {relative!r}: " + f"{owners[relative]} and {component_id}" + ) + if key in folded: + raise BundleError( + f"case/NFC collision on {relative!r}: " + f"{folded[key]} and {component_id}" + ) + owners[relative] = component_id + folded[key] = component_id + files[relative] = _git(component_dir, "cat-file", "blob", sha) + identities.append( + {"id": component_id, "path": path, "revision": revision, "files": len(modules)} + ) + return files, identities + + +def tree_digest(files: dict[str, bytes]) -> str: + digest = hashlib.sha256() + for relative in sorted(files): + digest.update(relative.encode()) + digest.update(b"\0") + digest.update(files[relative]) + digest.update(b"\0") + return "sha256:" + digest.hexdigest() + + +def 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() + + +def validate_aliases(aliases: list[dict], files: dict[str, bytes]) -> None: + seen: set[str] = set() + for alias in aliases: + if not isinstance(alias, dict): + raise BundleError("public alias entry must be an object") + module = alias.get("target_module") + function = alias.get("target_function") + names = alias.get("public_names") + if module not in files: + raise BundleError(f"public alias targets missing module: {module!r}") + if not isinstance(function, str) or not function: + raise BundleError(f"public alias for {module} has no target_function") + if not isinstance(names, list) or not names or not all( + isinstance(name, str) and name for name in names + ): + raise BundleError(f"public alias for {module}.{function} has invalid names") + for name in names: + if name in seen: + raise BundleError(f"public alias name declared twice: {name!r}") + seen.add(name) + if alias.get("expected_signature") != "params(值)": + raise BundleError( + f"public alias {module}.{function} must keep expected_signature params(值)" + ) + if alias.get("effects") != ["host"]: + raise BundleError( + f"public alias {module}.{function} must keep effects [host]" + ) + + +def build_manifest(config: dict, files: dict[str, bytes]) -> dict: + aliases = config.get("public_aliases", []) + validate_aliases(aliases, files) + return { + "name": config["name"], + "version": config["version"], + "digest": tree_digest(files), + "public_aliases": aliases, + "aliases_digest": aliases_digest(aliases), + } + + +def check_baseline(manifest: dict, baseline_path: Path) -> None: + baseline = load_json(baseline_path) + if baseline.get("version") == manifest["version"] and baseline.get( + "digest" + ) != manifest["digest"]: + raise BundleError( + f"Bundle content changed but version is still {manifest['version']}; " + "bump the version explicitly" + ) + + +def write_bundle(out: Path, manifest: dict, files: dict[str, bytes], force: bool) -> None: + if out.exists(): + if not force: + raise BundleError(f"output directory already exists: {out}") + shutil.rmtree(out) + out.parent.mkdir(parents=True, exist_ok=True) + staging = Path(tempfile.mkdtemp(prefix=".stdlib-build-", dir=str(out.parent))) + try: + for relative, data in files.items(): + target = staging / relative + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + (staging / MANIFEST).write_text( + json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", + encoding="utf-8", + ) + os.replace(staging, out) + except BaseException: + shutil.rmtree(staging, ignore_errors=True) + raise + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", required=True, help="Bundle output directory") + parser.add_argument("--root-commit", default=None) + parser.add_argument("--worktree", action="store_true") + parser.add_argument("--config", default=None) + parser.add_argument("--baseline-manifest", default=None) + parser.add_argument("--force", action="store_true") + parser.add_argument("--root", default=str(ROOT), help=argparse.SUPPRESS) + args = parser.parse_args(argv) + if args.worktree and args.root_commit: + parser.error("--worktree and --root-commit are mutually exclusive") + root = Path(args.root).resolve() + revision = None + if not args.worktree: + revision = args.root_commit or _git(root, "rev-parse", "HEAD").decode().strip() + try: + components = read_catalog(root, revision) + config = read_config(root, revision, Path(args.config) if args.config else DEFAULT_CONFIG) + files, identities = collect(root, components, root_commit=revision) + manifest = build_manifest(config, files) + if args.baseline_manifest: + check_baseline(manifest, Path(args.baseline_manifest)) + except BundleError as error: + raise SystemExit(f"build-stdlib: error: {error}") from error + write_bundle(Path(args.out), manifest, files, args.force) + summary = { + "name": manifest["name"], + "version": manifest["version"], + "tree_digest": manifest["digest"], + "aliases_digest": manifest["aliases_digest"], + "root_commit": revision, + "components": identities, + "files": sorted(files), + } + print(json.dumps(summary, ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/scripts/stdlib-bundle.json b/scripts/stdlib-bundle.json new file mode 100644 index 0000000..6684ddb --- /dev/null +++ b/scripts/stdlib-bundle.json @@ -0,0 +1,13 @@ +{ + "name": "marqdo-stdlib", + "version": "0.2.0", + "public_aliases": [ + { + "public_names": ["print", "打印"], + "target_module": "io.mq.md", + "target_function": "写值", + "expected_signature": "params(值)", + "effects": ["host"] + } + ] +} diff --git a/tests/integration/composition/aliases.mq.md b/tests/integration/composition/aliases.mq.md new file mode 100644 index 0000000..707dc57 --- /dev/null +++ b/tests/integration/composition/aliases.mq.md @@ -0,0 +1,9 @@ +# @exec aliases + +## main + +> **打印("alias-打印")** + +> **print("alias-print")** + +`return None` diff --git a/tests/integration/composition/cases/aliases.json b/tests/integration/composition/cases/aliases.json new file mode 100644 index 0000000..c8bc889 --- /dev/null +++ b/tests/integration/composition/cases/aliases.json @@ -0,0 +1,13 @@ +{ + "schema": "marqdo.stdlib-test-case", + "schema_version": 1, + "name": "aliases", + "file": "aliases.mq.md", + "args": [], + "stdin": "", + "env": {}, + "expected_stdout": "alias-打印\nalias-print\n", + "expected_terminal": { + "type": "none" + } +} diff --git a/tests/integration/composition/cases/default-bundle.json b/tests/integration/composition/cases/default-bundle.json new file mode 100644 index 0000000..e882617 --- /dev/null +++ b/tests/integration/composition/cases/default-bundle.json @@ -0,0 +1,51 @@ +{ + "schema": "marqdo.stdlib-test-case", + "schema_version": 1, + "name": "default-bundle", + "file": "default-bundle.mq.md", + "args": [], + "stdin": "", + "env": {}, + "expected_stdout": "default-bundle\n", + "expected_terminal": { + "items": [ + { + "decimal": "2", + "type": "int" + }, + { + "decimal": "195", + "type": "int" + }, + { + "decimal": "169", + "type": "int" + }, + { + "type": "text", + "value": "é" + }, + { + "type": "text", + "value": "[\"ok\", 3]" + }, + { + "type": "text", + "value": "[1, 2]" + }, + { + "type": "text", + "value": "a/b/c" + }, + { + "type": "text", + "value": "2026-11-21T08:00:00.123Z" + }, + { + "decimal": "2", + "type": "int" + } + ], + "type": "list" + } +} diff --git a/tests/integration/composition/cases/table.json b/tests/integration/composition/cases/table.json new file mode 100644 index 0000000..fbfebd3 --- /dev/null +++ b/tests/integration/composition/cases/table.json @@ -0,0 +1,314 @@ +{ + "schema": "marqdo.stdlib-test-case", + "schema_version": 1, + "name": "table", + "file": "table.mq.md", + "args": [], + "stdin": "", + "env": {}, + "expected_stdout": "", + "expected_terminal": { + "items": [ + { + "header": [ + "分数" + ], + "rows": [ + [ + { + "decimal": "87", + "type": "int" + } + ], + [ + { + "decimal": "92", + "type": "int" + } + ], + [ + { + "decimal": "71", + "type": "int" + } + ] + ], + "type": "table" + }, + { + "header": [ + "名称", + "分数" + ], + "rows": [ + [ + { + "type": "text", + "value": "甲" + }, + { + "decimal": "87", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "乙" + }, + { + "decimal": "92", + "type": "int" + } + ] + ], + "type": "table" + }, + { + "header": [ + "名称", + "分数" + ], + "rows": [ + [ + { + "type": "text", + "value": "丙" + }, + { + "decimal": "71", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "甲" + }, + { + "decimal": "87", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "乙" + }, + { + "decimal": "92", + "type": "int" + } + ] + ], + "type": "table" + }, + { + "header": [ + "名称", + "分数" + ], + "rows": [ + [ + { + "type": "text", + "value": "甲" + }, + { + "decimal": "87", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "乙" + }, + { + "decimal": "92", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "丙" + }, + { + "decimal": "71", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "丁" + }, + { + "decimal": "65", + "type": "int" + } + ] + ], + "type": "table" + }, + { + "header": [ + "名称", + "分数" + ], + "rows": [ + [ + { + "type": "text", + "value": "甲" + }, + { + "decimal": "99", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "乙" + }, + { + "decimal": "92", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "丙" + }, + { + "decimal": "71", + "type": "int" + } + ] + ], + "type": "table" + }, + { + "header": [ + "名称", + "分数", + "名称", + "等级" + ], + "rows": [ + [ + { + "type": "text", + "value": "甲" + }, + { + "decimal": "87", + "type": "int" + }, + { + "type": "text", + "value": "甲" + }, + { + "type": "text", + "value": "B" + } + ], + [ + { + "type": "text", + "value": "乙" + }, + { + "decimal": "92", + "type": "int" + }, + { + "type": "text", + "value": "乙" + }, + { + "type": "text", + "value": "A" + } + ] + ], + "type": "table" + }, + { + "entries": { + "a": { + "items": [ + { + "decimal": "1", + "type": "int" + }, + { + "decimal": "3", + "type": "int" + } + ], + "type": "list" + }, + "b": { + "items": [ + { + "decimal": "2", + "type": "int" + } + ], + "type": "list" + } + }, + "type": "map" + }, + { + "header": [ + "名称", + "分数" + ], + "rows": [ + [ + { + "type": "text", + "value": "甲" + }, + { + "decimal": "87", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "乙" + }, + { + "decimal": "92", + "type": "int" + } + ], + [ + { + "type": "text", + "value": "丙" + }, + { + "decimal": "71", + "type": "int" + } + ] + ], + "type": "table" + }, + { + "type": "text", + "value": "| 名称 | 分数 |\n| --- | --- |\n| 甲 | 87 |\n| 乙 | 92 |\n| 丙 | 71 |" + } + ], + "type": "list" + } +} diff --git a/tests/integration/composition/default-bundle.mq.md b/tests/integration/composition/default-bundle.mq.md new file mode 100644 index 0000000..c9e16dd --- /dev/null +++ b/tests/integration/composition/default-bundle.mq.md @@ -0,0 +1,28 @@ +--- +import: + io: "std:io" + format: "std:format" + json: "std:data/json" + text_lib: "std:text" + utf8: "std:text/utf8" + path: "std:path" + datetime: "std:datetime" +--- + +# @exec bundle + +## main + +**内存 = memory.new(1, 4)** + +**长度 = text_lib.utf8编码("é", 内存, 0)** + +**解码 = utf8.解码(内存, 0, 长度)** + +**对象 = json.解析("[1, 2]")** + +**时间 = datetime.格式化(1795248000123)** + +> **io.写值("default-bundle")** + +`return [长度, 内存[0], 内存[1], 解码.value, format.显示(["ok", 3]), json.格式化(对象.value), path.连接(["a", "b", "c"]), 时间, format.字节长度("é")]` diff --git a/tests/integration/composition/table.mq.md b/tests/integration/composition/table.mq.md new file mode 100644 index 0000000..ccb6b3b --- /dev/null +++ b/tests/integration/composition/table.mq.md @@ -0,0 +1,31 @@ +--- +import: + table_lib: "std:collections/table" + gfm_lib: "std:data/table" +--- + +# @exec table + +## main + +**数据 = 表(["名称", "分数"], [["甲", 87], ["乙", 92], ["丙", 71]])** + +**选择 = table_lib.选择列(数据, 1)** + +**过滤 = table_lib.过滤数值大于(数据, 1, 80)** + +**排序 = table_lib.排序(数据, 1)** + +**追加 = table_lib.追加行(数据, ["丁", 65])** + +**设置 = table_lib.设置单元格(数据, 0, 1, 99)** + +**左 = 表(["名称", "分数"], [["甲", 87], ["乙", 92]])** + +**右 = 表(["名称", "等级"], [["乙", "A"], ["甲", "B"]])** + +**连接 = table_lib.连接(左, 右, 0, 0)** + +**分组 = table_lib.分组(表(["类别", "值"], [["a", 1], ["b", 2], ["a", 3]]), 0, 1)** + +`return [选择, 过滤, 排序, 追加, 设置, 连接, 分组, 数据, gfm_lib.转GFM(数据)]` diff --git a/tests/integration/test_build_stdlib.py b/tests/integration/test_build_stdlib.py new file mode 100644 index 0000000..be8b15b --- /dev/null +++ b/tests/integration/test_build_stdlib.py @@ -0,0 +1,368 @@ +"""Contract tests for the root-owned, unique stdlib Bundle producer. + +These tests build real temporary Git repositories so the producer is exercised +through its real identity path: root catalog + exact gitlinks + component module +trees. They never call a network remote and never use the repository's own +Bundles. +""" + +import importlib.util +import json +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "build-stdlib.py" +SPEC = importlib.util.spec_from_file_location("build_stdlib", SCRIPT) +producer = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(producer) + +GIT_ENV = { + "GIT_AUTHOR_NAME": "test", + "GIT_AUTHOR_EMAIL": "test@example.invalid", + "GIT_COMMITTER_NAME": "test", + "GIT_COMMITTER_EMAIL": "test@example.invalid", +} + + +def git(cwd, *args, check=True): + env = os.environ.copy() + env.update(GIT_ENV) + result = subprocess.run( + ["git", "-C", str(cwd), *args], capture_output=True, env=env + ) + if check and result.returncode != 0: + raise AssertionError( + f"git {' '.join(args)} failed: {result.stderr.decode(errors='replace')}" + ) + return result + + +def init_repo(path: Path) -> Path: + path.mkdir(parents=True, exist_ok=True) + git(path, "init", "-q") + return path + + +def commit_all(repo: Path, message: str = "fixture") -> str: + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", message) + return git(repo, "rev-parse", "HEAD").stdout.decode().strip() + + +def write(path: Path, data) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data if isinstance(data, bytes) else data.encode()) + + +def component(repo: Path, files: dict) -> str: + init_repo(repo) + for relative, data in files.items(): + write(repo / relative, data) + return commit_all(repo) + + +def catalog(*components: dict) -> str: + blocks = [] + for component_spec in components: + lines = ["[[component]]"] + for key, value in component_spec.items(): + if isinstance(value, list): + rendered = "[" + ", ".join(json.dumps(item) for item in value) + "]" + else: + rendered = json.dumps(value) + lines.append(f"{key} = {rendered}") + blocks.append("\n".join(lines)) + return "\n\n".join(blocks) + "\n" + + +def root_repo(path: Path, catalog_text: str, links: dict, config: dict) -> str: + init_repo(path) + write(path / "components.toml", catalog_text) + write(path / "scripts/stdlib-bundle.json", json.dumps(config, indent=2)) + for relative, sha in links.items(): + git(path, "update-index", "--add", "--cacheinfo", f"160000,{sha},{relative}") + git(path, "add", "components.toml", "scripts/stdlib-bundle.json") + git(path, "commit", "-q", "-m", "root fixture") + return git(path, "rev-parse", "HEAD").stdout.decode().strip() + + +def base_config(version="0.1.0", aliases=None) -> dict: + return { + "name": "marqdo-stdlib", + "version": version, + "public_aliases": aliases or [], + } + + +def std_component(component_id: str, path: str, state="active") -> dict: + return { + "id": component_id, + "path": path, + "kind": "stdlib", + "state": state, + "owner": "test", + "scope": "fixture", + "requires": ["cli"], + "checks_with": [], + "release": "base", + } | ({"entry": "scripts/test.sh"} if state == "active" else {}) + + +class ProducerTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = Path(self.tmp.name) / "root" + self.root.mkdir() + + def tearDown(self): + self.tmp.cleanup() + + def build(self, *extra): + import contextlib + import io + + out = Path(self.tmp.name) / ( + "out-" + str(len(list(Path(self.tmp.name).glob("out-*")))) + ) + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer): + status = producer.main( + ["--out", str(out), "--root", str(self.root), *extra] + ) + self.assertEqual(status, 0) + return buffer.getvalue(), out + + def make_two_components(self): + text = component( + self.root / "stdlib/text", + { + "modules/text.mq.md": "# @exec text\n", + "modules/text/utf8.mq.md": "# @exec utf8\n", + "modules/README.md": "not published\n", + }, + ) + io = component( + self.root / "stdlib/io", + { + "modules/io.mq.md": "# @exec io\n", + "modules/io/console.mq.md": "# @exec console\n", + }, + ) + return text, io + + def two_component_root(self, text_sha, io_sha, version="0.1.0", aliases=None): + cat = catalog( + std_component("std-text", "stdlib/text"), + std_component("std-io", "stdlib/io"), + ) + return root_repo( + self.root, + cat, + {"stdlib/text": text_sha, "stdlib/io": io_sha}, + base_config(version, aliases), + ) + + def test_builds_deterministic_bundle_and_excludes_non_modules(self): + text_sha, io_sha = self.make_two_components() + self.two_component_root(text_sha, io_sha) + summary_one, out_one = self.build() + payload = json.loads(summary_one) + self.assertEqual(payload["files"], [ + "io.mq.md", + "io/console.mq.md", + "text.mq.md", + "text/utf8.mq.md", + ]) + self.assertNotIn("README.md", payload["files"]) + manifest = json.loads((out_one / "stdlib.json").read_text()) + self.assertEqual(manifest["name"], "marqdo-stdlib") + self.assertEqual(manifest["version"], "0.1.0") + self.assertEqual(manifest["digest"], payload["tree_digest"]) + self.assertEqual( + manifest["aliases_digest"], producer.aliases_digest([]) + ) + summary_two, out_two = self.build() + self.assertEqual( + json.loads(summary_two)["tree_digest"], payload["tree_digest"] + ) + for relative in payload["files"]: + self.assertEqual( + (out_one / relative).read_bytes(), (out_two / relative).read_bytes() + ) + self.assertEqual( + (out_one / "stdlib.json").read_bytes(), + (out_two / "stdlib.json").read_bytes(), + ) + + def test_worktree_mode_requires_clean_components(self): + self.make_two_components() + write( + self.root / "components.toml", + catalog( + std_component("std-text", "stdlib/text"), + std_component("std-io", "stdlib/io"), + ), + ) + write( + self.root / "scripts/stdlib-bundle.json", + json.dumps(base_config(), indent=2), + ) + out = Path(self.tmp.name) / "w" + producer.main(["--out", str(out), "--root", str(self.root), "--worktree"]) + self.assertTrue((out / "text.mq.md").is_file()) + write(self.root / "stdlib/text/modules/dirty.mq.md", "# @exec dirty\n") + with self.assertRaises(SystemExit): + producer.main([ + "--out", str(Path(self.tmp.name) / "w2"), + "--root", str(self.root), + "--worktree", + ]) + + def test_planned_component_is_not_published(self): + text_sha, _ = self.make_two_components() + planned_sha = component( + self.root / "stdlib/net", {"modules/net/tcp.mq.md": "# @exec tcp\n"} + ) + cat = catalog( + std_component("std-text", "stdlib/text"), + std_component("std-net", "stdlib/net", state="planned"), + ) + root_repo( + self.root, + cat, + {"stdlib/text": text_sha, "stdlib/net": planned_sha}, + base_config(), + ) + summary, out = self.build() + self.assertEqual(json.loads(summary)["files"], ["text.mq.md", "text/utf8.mq.md"]) + self.assertFalse((out / "net/tcp.mq.md").exists()) + + def test_duplicate_and_case_colliding_paths_are_rejected(self): + text_sha, _ = self.make_two_components() + clash_sha = component( + self.root / "stdlib/other", {"modules/Text.mq.md": "# @exec clash\n"} + ) + cat = catalog( + std_component("std-text", "stdlib/text"), + std_component("std-other", "stdlib/other"), + ) + root_repo( + self.root, + cat, + {"stdlib/text": text_sha, "stdlib/other": clash_sha}, + base_config(), + ) + with self.assertRaises(SystemExit): + self.build() + + def test_non_nfc_and_symlink_entries_are_rejected(self): + import unicodedata + + decomposed = unicodedata.normalize("NFD", "text/café.mq.md") + text_sha = component( + self.root / "stdlib/text", + {"modules/text.mq.md": "# @exec text\n", f"modules/{decomposed}": "# x\n"}, + ) + io_sha = component( + self.root / "stdlib/io", {"modules/io.mq.md": "# @exec io\n"} + ) + self.two_component_root(text_sha, io_sha) + with self.assertRaises(SystemExit): + self.build() + + tmp = tempfile.TemporaryDirectory() + try: + root = Path(tmp.name) / "sr" + root.mkdir() + text = root / "stdlib/text" + init_repo(text) + write(text / "modules/text.mq.md", "# @exec text\n") + (text / "modules/link.mq.md").symlink_to("text.mq.md") + sha = commit_all(text) + io = component(root / "stdlib/io", {"modules/io.mq.md": "# @exec io\n"}) + cat = catalog( + std_component("std-text", "stdlib/text"), + std_component("std-io", "stdlib/io"), + ) + root_repo(root, cat, {"stdlib/text": sha, "stdlib/io": io}, base_config()) + with self.assertRaises(SystemExit): + producer.main(["--out", str(root / "bundle"), "--root", str(root)]) + finally: + tmp.cleanup() + + def test_active_component_without_modules_is_rejected(self): + text_sha, io_sha = self.make_two_components() + empty_sha = component(self.root / "stdlib/empty", {"README.md": "x\n"}) + cat = catalog( + std_component("std-text", "stdlib/text"), + std_component("std-io", "stdlib/io"), + std_component("std-empty", "stdlib/empty"), + ) + root_repo( + self.root, + cat, + { + "stdlib/text": text_sha, + "stdlib/io": io_sha, + "stdlib/empty": empty_sha, + }, + base_config(), + ) + with self.assertRaises(SystemExit): + self.build() + + def test_content_change_requires_explicit_version_bump(self): + text_sha, io_sha = self.make_two_components() + self.two_component_root(text_sha, io_sha) + _, out = self.build() + baseline = out / "stdlib.json" + changed = component( + self.root / "stdlib/io", + { + "modules/io.mq.md": "# @exec io\n# changed\n", + "modules/io/console.mq.md": "# @exec console\n", + }, + ) + git(self.root, "reset", "-q", "--hard", "HEAD") + self.two_component_root(text_sha, changed) + with self.assertRaises(SystemExit): + self.build("--baseline-manifest", str(baseline)) + new_root = self.two_component_root(text_sha, changed, version="0.2.0") + self.assertIsNotNone(new_root) + summary, out_two = self.build("--baseline-manifest", str(baseline)) + self.assertEqual(json.loads(summary)["version"], "0.2.0") + + def test_public_alias_must_target_a_published_module(self): + text_sha, io_sha = self.make_two_components() + alias = { + "public_names": ["print", "打印"], + "target_module": "io.mq.md", + "target_function": "写值", + "expected_signature": "params(值)", + "effects": ["host"], + } + self.two_component_root(text_sha, io_sha, aliases=[alias]) + summary, out = self.build() + manifest = json.loads((out / "stdlib.json").read_text()) + self.assertEqual( + manifest["aliases_digest"], json.loads(summary)["aliases_digest"] + ) + bad = dict(alias, target_module="missing.mq.md") + git(self.root, "reset", "-q", "--hard", "HEAD") + self.two_component_root(text_sha, io_sha, aliases=[bad]) + with self.assertRaises(SystemExit): + self.build() + + def test_digest_algorithm_vector(self): + import hashlib + + files = {"a.mq.md": b"content"} + expected = "sha256:" + hashlib.sha256(b"a.mq.md\0content\0").hexdigest() + self.assertEqual(producer.tree_digest(files), expected) + + +if __name__ == "__main__": + unittest.main()